Vladislavs Dovgalecs
Vladislavs Dovgalecs

Reputation: 1631

Extract specific lines (indices given) from a file (strings)

I have two files: lines.txt and idx.txt

lines.txt:
aaa ggg sss
ww ee ttt
qq ee gg ccc
vvv bb b www ee
ppp dff f gg qq
pp qq ee rr tt
ww qq ee rrr

idx.txt
2
4
5

I would like to use "idx.txt" to extract those specific lines from "lines.txt" file. The files are pretty big (tens of MB). Currently I am using the following line but it is slow:

awk 'NR=FNR{arr[FNR]=$0; next} {for(i in arr) if(i==$1) print arr[i]}' lines.txt idx.txt

I am generating the "idx.txt" files using a script, hence the extraction of the lines should be fast.

Has somebody more elegant solution?

Upvotes: 0

Views: 42

Answers (1)

Ed Morton
Ed Morton

Reputation: 204154

awk 'NR==FNR{a[$0];next} FNR in a' idx.txt lines.txt

Upvotes: 2

Related Questions