computing
  • 8

Batch To Read Line Number From TXT File.

  • 8

Is it possible to read in specific lines from a batch file? In this example, I am trying to read the fourth line in the text file. I use an IF-ELSE statement with a GOTO statement to create a loop, but this code does not work. Any assistance is greatly appreciated.

set /a LineNumber = 4
set FileName = “c:\mpsreports\temp.txt”
set /a counter = 0

:loop

echo %LineNumber%
echo %counter%
pause
if %LineNumber% == %counter% (
REM – read line for real
SET /p MyLine=<%FileName%
cls
echo %MyLine% >> myline.txt
pause
goto :end
)else(
REM – read line and disregard
SET /p MyLine=<%FileName%
set /a counter=%counter%+1
pause
goto :loop
)

:end

Share

1 Answer

  1. When coding For loops (the method used to read text files in batch scripting) you can not access an environment variable that is modified inside the same block sequence without enabling the “Delayed Expansion” by a “setlocal” statement.

    Then the variables marked by ! symbol are interpreted as “dynamic” and expanded at run time while the ones marked by conventional % are expanded before the loop starts and never modified.

    To avoid confusion you may mark all variables as dynamic when the setlocal is coded (e.g. !FileName! or !LineNumber!). That is the most common pitfall in coding batches where there are sequences of statements embraced by parenthesis.

    To get a short tutorial on the issue at prompt type “set /?”. To know many interesting things about batch commands type the command code followed by the /? switch (e.g. if /? or call /?).

    I suggest to follow this road even for well known statements as batch scripting under NT kernel systems (Windows 2000/XP/Vista/7) is more powerful than its native ancestor under plain DOS or Windows 9X/ME environments.

    • 0