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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you are using the one-liner on the command prompt directly (so variables have a single %) and if %A is a command with a space in the directory name, then you might want to enclose the %A in the DO part into double-quotes: ....do ( "%A") ..... Thanks Andriy. Helped me.
8

If you try Andriy M's answer and get errors like

find: '/V': No such file or directory
find: 'summary': No such file or directory

then it's most likely you have Cygwin, MSYS2 or similar added to your Windows %path% and the batch file's not using the Windows find command. If you modify your script to use the absolute path of the Windows find then the error will go away:

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

1 Comment

1

You can also just embed a double-quoted string inside the single-quotes string, as in:

FOR /f "delims=" %%A in ('"dir /b my_dir\*.csv | find /I /V "summary""') do @(
    ECHO Do something with "%%A"
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.