Show the first word on each line

Posted on

Apr,30

 at

3:13 pm

by

jimazing

Building on the Not Dir command from last Friday… Andrew asked me today if I would help him come up with a way to parse a text file and show only certain lines that have the words “,smack”, “,my” or “,asprin” (notice that each of these is right after a comma). Oh yeah, the kicker is that he just wanted the first word on each line. Here’s the command:

for /f “tokens=1 delims=,” %g in (’findstr /E /I “smack my asprin” foobar.txt’) do @echo %g

I’ll take it apart and explain what makes it go starting with the inside command…

findstr /E /I “smack my asprin” foobar.txt

This command looks at each line in the file named foobar.txt and displays the lines that have any of these words in it. The words must be at the end of the line and we don’t care whether they are capitalized or not.

for /f “tokens=1 delims=,” %g in (’some command‘) do @echo %g

This is what the rest of the command does. The for command loops through each line. It echoes the first “token” on the line that is delimited by a comma. In English, that means that each line is subdivided by commas (delims=,) and we want to work with everything that comes before the first comma (tokens=1) saved in a variable (%g). What we want to do with that token is display it (echo %g).

So how does it know which “lines” to do all this stuff to? After the “in” word, comes some command in parentheses and single quotes. The fact that it is in single quotes makes the “for” command treat it like a command and use the output.

Special note: If you use this command inside a batch file, you’ll need to change the “%g” to “%%g”. No, I don’t know why.

Thanks to

Leave a Reply