Alex Rivera | Logout

Batch script with for loop and pipe

Asked 2011-05-17T05:52:55.277
36

I want to process all CSV files in a directory whose file name does not contain the word “summary”. Inside the command prompt, I can type the following command:

dir /b my_dir\*.csv | find /V "summary"

When I try to transfer the above command into a batch file, I run into the problem that the pipe command is not supported in the for loop. That means that I cannot do the following:

FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)

Can somebody shed some light to me on how to solve the problem above?

Edit
Report

1 Answer

73

You need to escape the | character to prevent its being interpreted at the time of parsing the loop command. Use ^ to escape it:

FOR /f "delims=" %%A in ('dir /b "my_dir\*.csv" ^| find /V "summary"') do (
rem do what you want with %%A here
)

Once escaped, the | becomes part of the '-delimited string. It is only interpreted as a special symbol when that string is parsed separately from the loop, as a "sub-command", according to the syntax. And that is done after parsing the loop.

answered 2011-05-17T06:31:09.507

Your Answer