computing
  • 3

Solved FOR Loop – Variable Number Of Lines To Skip

  • 3

I’m working on a batch script where I use a variable to tell the FOR how many lines to skip.

for /f "skip=!lines! tokens=1-3* delims=," %%A in (_!file!.txt)

However this does not seem to work. When I put a static number (replacing !lines! with a number) it works. Is there a way to make this work?

99 little bugs in the code,
99 little bugs.
Take one down, patch it around,
129 little bugs in the code.

Share

1 Answer

  1. Ok, having looked more closely, you need TWO loops (which you prob’ly already know). I made a testing setup and ran the following with fair results:

    @echo off & setlocal
    :: this version is NOT optimized! It passes through all files for each line
    :: until the last line in the longest file is reached.
    :: for speed, use ATTRIB to select the files and then disqualify each file
    :: when it reaches its last line.
    set c=0
    :: var TEST is a flag that says no files have any more unprocessed lines
    set test=—-

    :: main loop – pass through all files
    :aa

    :: clear flag for the next iteration of ‘aa’
    set test=
    :: secondary loop – pass through all files pulling the current line from each
    for %%z in (*.txt) do (
    call :xx !c! %%z
    )
    set /a c+=1
    if defined test goto :aa
    goto :eof

    :xx
    set /a k=%1+1
    :: ‘SKIP=0’ is not accepted by batch, so this is a workaround
    set sk=
    if %1 neq 0 set sk=skip=%1
    for /f “%sk% tokens=*” %%a in (%2) do (
    if “%%a” equ “” echo no more lines in file %2 & goto :eof
    echo line %k% from file %2: %%a
    pause
    :: set flag for loop-repeat: does not have to be %%a. Just needs some/any value
    set test=%%a
    goto :eof
    )

    • 0