Batch to read line number from TXT file.

Microsoft Windows vista business - 3 pac...
February 26, 2010 at 09:25:26
Specs: Windows Vista
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


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


See More: Batch to read line number from TXT file.

Report •

February 26, 2010 at 13:13:05
The following script does the job, but as you can see the code required is far away what you supposed to be

@echo off & setlocal EnableDelayedExpansion
set LineNumber=4
set FileName=C:\mpsreports\temp.txt
set counter=0

for /F "delims=" %%j in ('type "%FileName%"') do (
  set /A counter+=1
  if !counter! equ %LineNumber% (echo.%%j> "myline.txt" & goto :END)

The For /F ignores blank lines so you have to take that into account for your LineNumber and avoid spaces around the = symbol.

Report •

February 27, 2010 at 19:28:24
Thank you. I do not understand why you used the syntax !counter! instead of %counter%. I am new to batch file programming and I'm curious to know the difference between the different syntax.

Thank you in advanced for any advice.

Report •

February 28, 2010 at 06:52:55
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.

Report •

Related Solutions

Ask Question