Your code actually finds all lines that do NOT contain "printline" because of the /v option. I'm going to assume you actually want the line(s) with "printliine", so I will remove the /v option. Add it back if needed.
The solution is to prefix each line that is found with the line number using the FINDSTR /n option. You then simply adjust your FOR /F options to compensate and add an IF to conditionally process the matching line only if it is line number %x%. If the command can contain a colon, then the solution will be a bit more complicated because FOR /F options will not allow you to parse properly because the line number prefix also includes a colon.
Assuming your command cannot contain a colon, then this should work (untested). I'm arbitrarily setting x to 50 in this code. I also undefine command and value so that they are guaranteed to be undefined if the matching line is not found.
Code: Select all
@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=1,2* delims=: " %%a in ('findstr /n /i "printline"') do if "%%a"=="%x%" (
set "command=%%b"
set "value=%%c"
setlocal enabledelayedexpansion
echo !value!
endlocal
goto :break
)
:break
(file continues)
An alternative way, perhaps more efficient, would be to use a 2nd FINDSTR to find the correct line instead of an IF condition. This solution does not require the GOTO.
Code: Select all
@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=1,2* delims=: " %%a in ('findstr /n /i "printline" ^| findstr /b "%x%:"') do (
set "command=%%b"
set "value=%%c"
setlocal enabledelayedexpansion
echo !value!
endlocal
)
(file continues)
I'm wondering if your command is "printline" followed by a space. If so, then a more precise solution would look for "printline " at the beginning of each line:
Code: Select all
@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=1,2* delims=: " %%a in ('findstr /n /i /b "printline " ^| findstr /b "%x%:"') do (
set "command=%%b"
set "value=%%c"
setlocal enabledelayedexpansion
echo !value!
endlocal
)
(file continues)
Dave Benham