开发者

Printing specific lines of a textual file in Windows Batch

I'm trying to find a fairly efficient way of printing specific lines of a textual file in Windows Batch. It must be Windows Batch and no other tools (gwk.exe, perl, python, javascript, etc. etc.). I have a li开发者_如何学编程st of line numbers (1, 7, 15, 20, etc.) which can be fairly long (dozens if not more).

Any ideas?

Thanks!


Here's a script which shows how you can do it. It's not the most efficient in the world but command scripts rarely are :-)

@setlocal enableextensions enabledelayedexpansion
@echo off
set lines=1 7 15 20
set curr=1
for /f "delims=" %%a in ('type infile.txt') do (
    for %%b in (!lines!) do (
        if !curr!==%%b echo %%a
    )
    set /a "curr = curr + 1"
)
endlocal

When run over the file containing line N for N ranging from 1 to 24, you get:

line 1
line 7
line 15
line 20

as expected.

I wouldn't be using this for a very large number of line numbers (since the inner loop runs that many times for every line in the file).


You can use a couple of simple batch files:

main.bat:

@echo off
set k=0
for /f "tokens=1*" %%i in (%1) do call helper %%i %%j

helper.bat:

@echo off
for /f %%j in (numbers.txt) do if /I %k% equ %%j echo %1 %2
set /A k=%k%+1

Then supply a numbers.txt file which contains the line numbers you want to print, one per line, and call it as:

main.bat my_file.txt

where my_file.txt is the file you want to extract lines from.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜