Search code examples
windowsbatch-filecommand

How to create batch that runs multiple commands for output files


I am creating a batch file and I need it to run 2 different scripts on files in a folder with potentially hundreds of files.

The 1st script (abc2xyz) converts a file from .abc to .xyz

The 2nd script (procxyz) processes the .xyz

for %%f in (*.abc) do (
    abc2xyz %%f
    procxyz *.xyz
    )

The 1st script outputs .xyz just fine.

The 2nd script repeats running on ALL converted xyz files in the folder following each converted file instead of running on just the one that was just converted.

I can probably guess *.xyz is a problem, but how would I change this to process on the recent converted file instead of all .xyz files each time a file is converted?


Solution

  • Each time you enter the loop, each command is executed, in this case, you are using a wildcard *.xyz and therefore each xyz file will be processed, so if you want to do it per file, you need to use variable expansion.

    @echo off
    for %%f in (*.abc) do (
        abc2xyz "%%~f"
        procxyz "%%~nf.xyz"
    )
    

    Note, the surrounding double quotes on the second command is important, if your file has a space, your file will not be processed.

    You can test the actual results, without modifying them, by running the following:

    @echo off
    for %%f in (*.abc) do (
       echo "%%~f"
       echo "%%~nf.xyz"
    )
    

    You can read about variable expansion by running, from for /? from cmd, then scroll down and read the substitution section.