快速业务通道

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

作者 佚名 来源 批处理 浏览 发布时间 2013-07-09
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
)

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号