欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

批处理提取不同行上的内容的代码

程序员文章站 2022-06-16 15:45:56
for instance:- for /f "delims=" %%a in (input.txt) do ... for /f "delims=" %%a in ('ty...
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 ^< input.txt') do ...

however, only the last method (using the more command) will give consistent results across windows nt, 2000, xp and 2003. the first method does not recognise unicode files. also, the usebackq switch must be used if the input filename contains spaces. the second method, using the type command, also fails to recognise unicode files on windows 2000, xp and 2003 if the input file does not begin with a bit order mark (bom).

in all the examples, assume the contents of of the file numbers.txt to be:-

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 ^< numbers.txt') do (
if not defined first set first=%%a
)
echo/%first%

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 ^< 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
)

displaying the last line

this example prints ten.

@echo off & setlocal enableextensions
for /f "delims=" %%a in ('more ^< numbers.txt') do set "last=%%a"
echo/%last%

displaying the last x lines

this example prints 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
)

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% ^< numbers.txt') do (
if not defined line set "line=%%a"
)
echo/%line%

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% ^< 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
)