Batch File, dir | findstr within a for loop

Let me preface by admitting that I am a complete noob at batch files... and programming language in general. I am trying to write a batch file that allows the user to input a partial filename, and it will search dozens of sub-directories, find and open all of the pdf files whose name contains the user input. I am expecting that it would find between 2 and 8 different pdf files.

I can use the following to return the file-paths,

set /p Number="Enter the Job-Shaft Number "
echo Searching folders
dir /b /s "*.pdf" | findstr /i "%Number%"

but when I try to wrap it in a for loop so that I can actually do something with it, I'm running into problems:

for %%G in ('dir /b /s "*.pdf" | findstr /i "%Number%"') do echo %%G

It doesn't seem to like the pipe. Any suggestions?

P.S. I want it to actually open up the pdf files not just echo, but I haven't gotten that far with it yet. If I can't get it to work now, there's no sense in me making things more complicated, yet.

2

1 Answer

To run the command you need to

  1. insert /f just behind for and also
  2. insert "delims=" to not tokenize the output
    (with default "tokens=1 and delims= " it would cut off after white space)
  3. escape the pipe symbol ^| to pass it to the secondary cmd.exe which is executed behind the scenes.

for /f "delims=" %%G in ('dir /b /s "*.pdf" ^| findstr /i "%Number%"') do echo %%G

If %Number% indeed represents a number there is no need to use the /i switch

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like