Subtitle: “Getting more precise and limited output from FindStr results against multiple files…” …which is a lousy subtitle, I know.
Sometimes, you just want to parse multiple files in a folder for particular lines of content, and do something with those parsed results (perhaps dump to file, or use as input for a loop). However, one of the challenges can be that while using
FindStr against multiple files, the output shows the source filename on the line with the result as a courtesy (thanks a lot). And lacking Linux-like flexibility of control over the command options, we’re almost out of luck before we ever start — but there are ways around that… First, however, I’ll demonstrate the challenge.
DOS is Not Linux
Starting out with a test folder, containing two text files each with a few lines we want, and few we don’t.
C:\Test>dir /B file.wri other.wri
Assume that we are looking for any line in these files that contains the
tar command; so using
findstr, we issue our search:
C:\Test>findstr /C:"tar " *.wri
…and as described, the result shows the filename on each line:
file.wri:tar this file.wri:tar that other.wri:tar some other stuff other.wri:#commented out tar thingy
This would not be good if we were trying to take the results as issued commands or as input to other commands. So, we’ll try to meet
findstr on its own terms, and using good ol’
type and try to mask the fact that we are sending individual files to
So piping the one into the other, we issue the command:
C:\Test>type *.wri |findstr /C:"tar "
…and the the result is just goofy:
tar this tar that not a line you want tar some other stuff #commented out tar thingy
But DOS Loops Rule
But all hope is not lost. If we loop through all the files individually, and stuff them each into
findstr one-by-one with each iteration of the loop,
findstr will be happy and give us pretty, clean, limited output. Yay! Just put this in a script to see what I mean:
@ECHO OFF @For /F "tokens=*" %%Q in ('dir /B c:\test\*.wri') Do @( findstr /C:"tar " %%Q )
…and of course, the result is exactly what I wanted:
tar this tar that tar some other stuff #commented out tar thingy