views:

6274

answers:

5

I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:

  • Display the base name 'f'
  • Perform an action on 'f.in'
  • Perform another action on 'f.out'

I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.

My, doesn't Stackoverflow make me lazy at figuring things out!! :)

A: 

Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.

According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:

for %%f in (*.in) do call process.cmd %%~nf

Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:

echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt

There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.

EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...

Nathan Fritz
A: 

There is a tool usually used in MS Servers (as far as I can remember) called forfiles:

The link above contains help as well as a link to the microsoft download page.

+3  A: 

You can use this line to print the contents of your desktop:

FOR %%c in (C:\windows\desktop\*.*) DO echo %%c

Once you have the %%c variable it's easy to perform a command on it (just replace the word echo with your program)

I'm not sure how this works with local variables, but if you just want the filename with no extension you can do this:

%~n1

or name + extension:

%~nx1

etc

Here are some links that may help:

http://home.att.net/~gobruen/progs/dos_batch/dos_batch.html

Mark Ingram
+13  A: 

Assuming you have two programs that process the two files, process_in.exe and process_out.exe:

    for %%f in (*.in) do (

            echo %%~nf
            process_in %%~nf.in
            process_out %%~nf.out
    )
Jim Buck
A: 

Expanding on Nathans post. The following will do the job lot in one batch file.

@echo off

if %1.==Sub. goto %2

for %%f in (*.in) do call %0 Sub action %%~nf
goto end

:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt

:end
Martin