Reputation: 35
I have a code that is supposed to read a big text file in groups. I have separated the problem part in a much smaller code containing only the for loop this problem occurs in. The code works in a way that it reads 100 lines, then goes out of the for loop, goes back, and skips 100 lines, reads next 100, then skips 200, reads next 100... etc etc. But there seems to be a problem with the options in the for loop. It gives me " was unexpected at this time. As in the title.
setlocal enabledelayedexpansion
set skipline=0
:loop
FOR /F "skip=%skipline%" %%G IN (doc1.txt) DO (
if NOT !line! GTR 100 (
set /a line+=1
echo line!line! %%G
) else goto :endloop
)
:endloop
set /a line=0
set /a skipline+=100
pause
goto :loop
I really would appreciate an answer, because I can't continue my work until I can fix this.
Upvotes: 1
Views: 206
Reputation: 67216
As MC ND indicated in his answer, the problem is that skip
FOR option can not skip 0 lines. A way to fix this point in your code is this:
setlocal enabledelayedexpansion
set skipline=0
set "skip="
:loop
set line=0
FOR /F "%skip%" %%G IN (doc1.txt) DO (
set /a line+=1
echo line!line! %%G
if !line! EQU 100 goto :endloop
)
:endloop
set /a skipline+=100
set "skip=skip=%skipline%"
pause
goto :loop
However, you may use a simpler method that consist in redirect the file into a subroutine, so you can read the lines there via a set /P
command placed in a FOR /L
loop that run faster than your method. When the end of the file is reached, set /P
set the errorlevel to 1, so this is a simple way to end the process.
setlocal EnableDelayedExpansion
call :ProcessFile < doc1.txt
goto :EOF
:ProcessFile
for /L %%i in (1,1,100) do (
set /P "line="
if errorlevel 1 goto endFile
echo line%%i !line!
)
pause
goto ProcessFile
:endFile
exit /B
Upvotes: 2
Reputation: 70953
for /f
will not allow you to skip 0 lines. Try with something like
setlocal enabledelayedexpansion
set "skiplines=0"
:loop
if %skipLines%==0 ( set "skip=" ) else (set "skip=skip=%skipLines%")
set /a line=0
(FOR /F "%skip% delims=" %%G IN (doc1.txt) DO (
set /a "line+=1"
echo line!line! %%G
if !line! EQU 100 goto :endloop
)) || goto endFile
:endloop
set /a skipLines+=100
pause
goto :loop
:endFile
echo File processed
The full skip
clause is stored in a variable depending on the number of lines to skip. If %skipLines%
is 0, then no skip
clause must be used.
There is a conditional execution operator at the end of the for
loop to test if the file has been completely processed. When the for /f
can not read anything from the file (we are skipping all the lines) it raises errorlevel and the goto endFile
is executed.
In any case, you should note that the for /f
will always load all the data in the file into memory. The skip
clause just indicates where to start to execute the code inside the do
clause.
Upvotes: 3