2

I got stuck in the windows batch(cmd) pattern search. I need to search for a pattern in a file and need to return the line number. I have used FINDSTR with /X option, but it is also appending the patterned matched line to the line number.

Also I don't have privilege to install any utility like unix-utilities so that I can use cut to extract the line number.

Abinash Bishoyi
  • 187
  • 1
  • 2
  • 13

2 Answers2

5
for /f "delims=:" %%a in ('findstr /n "pattern" "file"') do echo "pattern" found in line #%%a
Endoro
  • 37,015
  • 8
  • 50
  • 63
  • I'm not sure why it is not working... >for /f "delims=:" %%a in ('findstr /n /C:"Line 1" test') do echo "pattern" found in line #%%a %%a was unexpected at this time. Please have a look... – Abinash Bishoyi Aug 26 '13 at 13:53
  • 2
    @AbinashBishoyi - If run directly from the command line, then you need to use `%a` in both places. The percents are only doubled when used within a batch script. – dbenham Aug 26 '13 at 14:01
4

Endoro has posted a good pure batch solution.

Another option is to use a hybrid JScript/batch utility I wrote called REPL.BAT that performs regex search and replace on stdin and writes the result to stdout. It is purely script based, so no executables need to be installed. It works on any modern Windows machine from XP onward. REPL.BAT is available here.

Assuming REPL.BAT is in your current directory, or better yet, somewhere within your PATH:

findstr /n "pattern" "file.txt"|repl :.* ""
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390