tyee
tyee

Reputation: 331

Nested For loop for finding specific line in file

This code from Jeb -

set "lineNr=%1"
set /a lineNr-=1
for /f "usebackq delims=" %%a in (`more +%lineNr% text.txt`) DO (
  echo %%a
  goto :leave
)
:leave

is not working in my case. I want to include it in a nested for loop like this

for %%x in (*.md) do (
set "lineNr=7"
set /a lineNr-=1
for /f "usebackq delims=" %%a in (`more +%lineNr% "%%x"`) DO (
  echo %%a
  goto :leave
)
:leave
)

If I use the above I get error of

) was unexpected at this time.

If I do it this way

for %%x in (*.md) do (
    set "lineNr=7"
    set /a lineNr-=1
    for /f "usebackq delims=" %%a in (`more +%lineNr% "%%x"`) DO (
      echo %%a
      goto :leave
    )
    )
    :leave

then all the other *.md files will not be processed because I'm out of the loop I believe and it also does not work because the "LineNR' is removed for some reason as shown here from the cmd output -

set "lineNr=7"
 set /a lineNr-=1
 for /F "usebackq delims=" %a in (`more + "%x"`) DO (
echo %a
 goto :leave
)
)
:leave

Cannot access file G:\test\+

What am I doing wrong or is there a simpler way to grab a couple of lines and output them to a txt file?

Upvotes: 0

Views: 34

Answers (1)

Squashman
Squashman

Reputation: 14340

Not really understanding what you are doing with your number variable as it would always be 6 for every file you process but you also have a delayed expansion problem when using that variable because you are inside a code block.

You can solve your problem by breaking out your inner FOR command to a function.

@echo off
for %%x in (*.md) do CALL :routine "%%~x"
GOTO :EOF

:routine
set "lineNr=7"
set /a lineNr-=1
for /f "usebackq delims=" %%a in (`more +%lineNr% "%~1"`) DO (
  echo %%a
  goto :EOF
)

Upvotes: 1

Related Questions