2

I want to return the line number in a file that always has the same prefix, but the rest may vary.

Is it possible to search a file using only stock Windows components and Commandline operating utilities to return the line number of the matching part.

An example of the line I am searching for is:

</TR></TABLE><TABLE cellspacing... More code that may vary

The line in the file is the output of a generator and so I am not sure what has changed or may change every time it generates the file.

2 Answers2

1

FINDSTR is used to search for text in a file, printing out each line that matches the search. The /N option causes the line number to be prepended to each matching line of output as LineNumber:FullTextOfMatchingLine.

Since your search string includes a space, you must use the /C:"search string" option, otherwise the search string is interpreted as multiple search terms delimited by space.

You want the search to only match the beginning of the line, so you need the /B option. Alternatively you could add the /R option to treat the search as a regular expression and then use the ^ beginning-of-line anchor at the start of your search string.

findstr /b /c:"</TR></TABLE><TABLE cellspacing" "yourFile.htm"

You ask for only the line number, without the text of the matching line. You can use FOR /F to extract out the desired line number(s).

for /f "delims=:" %A in ('findstr /b /c:"</TR></TABLE><TABLE cellspacing" "yourFile.htm"') do @echo %A

If you put the command in a batch file then you must double the percents:

@echo off
for /f "delims=:" %%A in ('findstr /b /c:"</TR></TABLE><TABLE cellspacing" "yourFile.htm"') do echo %%A
dbenham
  • 11,384
0

Use findstr /N strings filename to search for instances of strings in the file filename.

Note: /N "Prints the line number before each line that matches"

For more usage information, run findstr /?

DavidPostill
  • 156,873
Steven
  • 27,892