How to use FINDSTR to search in a specific line?
The required code for findstr should be:
findstr /b /n "Hi" "example.txt"
Is there something that can search for "Hi" string only in the commanded line
Based on the wording of your question, I'm going to assume a few things:
- You want to find a string ONLY and nothing more on a specific line
- Since your example
FINDSTR
uses the/B
you string of "Hi" is at the begginning of the line only and then followed by a space for another word, etc. after it. - Since your example uses the
/N
swtich, I'm going to assume you only use it to print the lines which the matched strings are found so you can then run aboutFINDSTR
command to then get ONLY line 15.
Here are some example commands (not batch) to run to perform this
(You can simple copy and paste all these lines once you variable are plugged in accordingly to run without being a batch script.)
SET SearchFile=C:\Path\example.txt SET TmpSearchFile=%Temp%\~tmpSearch00.txt SET String=Hi SET LineNum=15 FINDSTR /B /N "%String%" "%SearchFile%" > "%TmpSearchFile%" FOR /F "USEBACKQ TOKENS=2 DELIMS=: " %A IN (`"FINDSTR /B "%LineNum%:%String%" "%TmpSearchFile%""`) DO ECHO %~A
This basically pipes the first FINDSTR
with the line number of the matching string at the beginning of all lines to a temp file (if it exists, it is overwritten). It then searches that temp file for the string of the line number, plus a colon and the string (i.e. "15:Hi"). Afterwards, I used a FOR /F
loop making the colon
and a space
the delimiter
with a token
of 2
. It will then ECHO
the string ONLY as you request (replace ECHO
with some other command if needed).