1.

Solve : How read a particular line from a text file??

Answer»

Hi Friend,

In batch code, is it possible to read a particular line from the text file.

For eg.,
Text file "test1.txt" contains the following text....

data1
data2
data3
data4
data5


I need to read the 3 line of the "test1.txt" file and print that line ALONE
(Ie.., It should echo the 3 line alone "data3")

Is there any option to RESOLVE this issue....

Thank in Advance.

Urs,
VinothIt is especially important that posters on this BOARD tell US their operating system. Batch code changes with each release from Microsoft, so what may work on one OS may not work on another.

This code will work for the test data provided:

Code: [Select]@echo off
setlocal enabledelayedexpansion
set count=0
for /f %%v in (test.txt) do (
call set /a count=%%count%%+1
if !count!==3 echo %%v
)

Good luck. Quote from: Sidewinder on June 16, 2008, 06:20:02 AM

Code: [Select]@echo off
setlocal enabledelayedexpansion
set count=0
for /f %%v in (test.txt) do (
call set /a count=%%count%%+1
if !count!==3 echo %%v
)

Why not increment the count like this?

Code: [Select]@echo off
setlocal enabledelayedexpansion
set count=0
for /f %%v in (test.txt) do (
set /a count=!count!+1
if !count!==3 echo %%v
)

Quote from: Dias de verano on June 16, 2008, 06:50:06 AM
Why not increment the count like this?

No particular reason. The result is the same, so I suggest it's a matter of style rather than efficiency.

Why do you ask?

I was curious why you used found that call set /a %%count%% statement.
Quote from: Dias de verano on June 16, 2008, 08:45:35 AM
I was curious why you used found that call set /a %%count%% statement.

Probably from deranged habit.

In the OP case, delayed expansion was necessary, but sometimes other approaches create interesting results:

Code: [Select]@echo off
set count=0
for /f %%v in (test.txt) do (
call set /a count=%%count%%+1
call echo %%count%%
)

The call to echo produces a running tally of the count variable. Without the call, results are less than stellar. If I could have, I'd have called the if statement, but it doesn't QUITE work.



Discussion

No Comment Found