It's too profound. I can't understand it!
Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
DOS stands for freedom, openness and progress. Let us work hard, learn from the openness and GNU spirit of FreeDOS and Linux, and together build and grow a free GNU GPL world!
DigestI
View 12,411 Replies 19
This page tells everyone how to read a certain line from a text file. There are many methods to use for/f to read the content of input.txt, for example:
for /f "delims=" %%a in (input.txt) do ...
for /f "delims=" %%a in ('type input.txt') do ...
for /f "delims=" %%a in ('more ^< input.txt') do ...
However, only the last method (using the more command) can get consistent results in different operating systems such as Windows NT, 2000, XP and 2003. The first method cannot recognize UNICODE-encoded files, and if the input file name contains spaces, the usebackq parameter must be used. The second method, using the type command, also does not recognize UNICODE files in Windows 2000, XP and 2003 if the file does not start with a byte order mark (BOM).
In all examples, assume the content of numbers.txt is:
one
two
three
four
five
six
seven
eight
nine
ten
Display the first line
This example outputs one.
@echo off & setlocal ENABLEEXTENSIONS
set "first="
for /f "delims=" %%a in ('more ^< numbers.txt') do (
if not defined first set first=%%a
)
echo/%first%
Display the first few lines
This example outputs one, two and three.
@echo off & setlocal ENABLEEXTENSIONS
set "lines=3"
set i=-1
set "ok="
for /f "delims=" %%a in ('more ^< numbers.txt') do (
set/a i+=1 & for /f %%z in ('echo/%%i%%') do (
if "%%z"=="%lines%" set ok=1
)
if not defined ok echo/%%a
)
Display the last line
This example outputs ten.
@echo off & setlocal ENABLEEXTENSIONS
for /f "delims=" %%a in ('more ^< numbers.txt') do set "last=%%a"
echo/%last%
Display the last few lines
This example outputs nine and ten.
@echo off & setlocal ENABLEEXTENSIONS
set "lines=2"
for /f %%a in ('find/c /v "" ^< numbers.txt') do set/a skip=%%a-lines
for /f "delims=" %%a in ('more/e +%skip% ^< numbers.txt') do (
echo/%%a
)
Display the nth line
This example outputs three. Note that the /e parameter of more is used here to skip the specified number of lines, and when used with for/f, it will fail if the value is less than 1.
@echo off & setlocal ENABLEEXTENSIONS
set LineNo=3
set "line="
set/a LineNo-=1
for /f "delims=" %%a in ('more/e +%LineNo% ^< numbers.txt') do (
if not defined line set "line=%%a"
)
echo/%line%
Display the nth line plus X lines
This example outputs 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% ^< numbers.txt') do (
set/a i+=1 & for /f %%z in ('echo/%%i%%') do (
if "%%z"=="%lines%" set ok=1
)
if not defined ok echo/%%a
)