new
new

Reputation: 1159

Get a line in a file by the use of the specific line number got in a loop

I need to extract a line into a file based on the line number that I got in a loop For. In fact, I get the line 7 from the first FOR command, so far so good and I have to read this line into myfile.txt. The reading operation is performed in the second FOR loop; this step does not work since I get output 'result.txt' empty

for /f "tokens=1* delims=:" %%a in (lines.txt) do set line=%%a& goto breakFor "%line%"

:breakFor
echo.%line%
for /f "tokens=*" %%a in ('findstr /n .* "myfile.txt"') do if "%%a"=="%1" set line=%%i
echo.%line%>result.txt

Here's a part of myfile.txt and lines.txt

lines.txt
7:I=output7
515:I=output515
837:I=output837
851:I=output851

myfile.txt is made of lines of text (I1,I2,I3,...)
I1=some text....
I2=text...

Could you please tell me why and help to fix that? Thanks

Upvotes: 0

Views: 81

Answers (2)

Aacini
Aacini

Reputation: 67226

The Batch file below do the following:

  • Read the first line of the file lines.txt
  • Get the number that appear before a semicolon
  • Use this number to locate that line in myfile.txt
  • Show that line

.

for /f "tokens=1* delims=:" %%a in (lines.txt) do set line=%%a& goto breakFor
:breakFor
echo.%line%
for /f "tokens=1* delims=:" %%a in ('findstr /n "^" "myfile.txt" ^| findstr "^%line%:') do set line=%%b
echo.%line%>result.txt

Is this what you want? I would prefer do it this way:

for /f "tokens=1* delims=:" %%a in (lines.txt) do set /A line=%%a-1& goto breakA
:breakA
echo.%line%
for /f "skip=%line% tokens=1* delims=:" %%a in ('findstr /n "^" "myfile.txt"') do set line=%%b& goto breakB
:breakB
echo.%line%>result.txt

Upvotes: 2

Endoro
Endoro

Reputation: 37589

try this and look at the output:

@echo off &setlocal
set "line=test"
goto breakFor "%line%"
:breakFor
echo "%~1"

Upvotes: 1

Related Questions