Thứ Năm, 5 tháng 6, 2008

Reading Files

This page shows how to read specific lines from a text file. There are many ways to have the for /f command read the input file, for instance:-

for /f "delims=" %%a in (input.txt) do ...

for /f "delims=" %%a in ('type input.txt') do ...

for /f "delims=" %%a in ('more ^<>

one
two
three
four
five
six
seven
eight
nine
ten

Displaying the first line

This example prints one.

@echo off & setlocal ENABLEEXTENSIONS
set "first="
for /f "delims=" %%a in ('more ^< first="%%a">

Displaying the first X lines

This example prints one, two and three.

@echo off & setlocal ENABLEEXTENSIONS
set "lines=3"
set i=-1
set "ok="
for /f "delims=" %%a in ('more ^< ok="1">

Displaying the last line

@echo off & setlocal ENABLEEXTENSIONS
for /f "delims=" %%a in ('more ^< last="%%a">
echo/%last%

Displaying the last X lines

@echo off & setlocal ENABLEEXTENSIONS
set "lines=2"
for /f %%a in ('find/c /v "" ^< skip="%%a-lines" delims="">

Displaying the Nth line

This example prints three. Note that instead of using the more command's /e switch, the skip option could have been used with the for /f command, however, this fails is it is set to any number less than one.

@echo off & setlocal ENABLEEXTENSIONS
set LineNo=3

set "line="
set/a LineNo-=1
for /f "delims=" %%a in ('more/e +%LineNo% ^< line="%%a">>

Displaying the Nth line plus X number of lines

This example prints five and six.

@echo off & setlocal ENABLEEXTENSIONS
set start=5
set "lines=2"
set/a i=-1,start-=1
set "ok="
for /f "delims=" %%a in ('more/e +%start% ^<>
set/a i+=1 & for /f %%z in ('echo/%%i%%') do (
if "%%z"=="%lines%" set ok=1
)
if not defined ok echo/%%a
)