Batch File, dir | findstr within a for loop
To run the command you need to
- insert
/f
just behind for and also - insert
"delims="
to not tokenize the output
(with default"tokens=1 and delims= "
it would cut off after white space) - 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
Gumbi
Updated on September 18, 2022Comments
-
Gumbi over 1 year
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.
-
harrymc over 5 yearsWhat errors are you getting?
-
Gumbi over 5 yearsIt's hard to tell, harrymc, it flashes so quickly, and then the window closes. but I think it says " | was unexpected at this time"
-
-
Gumbi over 5 yearsThanks for your help!
for /f "delims=" %%G in ('dir /b /s "*.pdf" ^| findstr /i "%Number%"') do echo %%G
is what worked!