tags:

views:

25

answers:

2

Hi Everyone,

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 list of line numbers (1, 7, 15, 20, etc.) which can be fairly long (dozens if not more).

Any ideas?

Thanks!

+2  A: 

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

paxdiablo
Thanks paxdiablo! It is indeed a bit problematic for a large number of lines, but for a smaller number its okay.
Yon
A: 

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.

Vicky
Thanks, but this complicates things dearly while working the same way the other answer does.
Yon