OpenSauce
OpenSauce

Reputation: 8623

Quickest/most concise bash one-liner for extracting specified lines from a file

I want to extract just the lines with specific line numbers from a file (I have about 20-50 line numbers, the file has 30,000 lines). So far, the most concise way I've found to do this is e.g.:

gawk 'BEGIN {split("13193,15791,16891", A, ",")} NR in A' <file_name>

but it seems like I should be able to further reduce the amount of typing involved. I've looked at sed but I think I need an -n and a -p for each line number, also thought about cat -n with grep but it's more verbose than the above. Does anyone know a better way?

Upvotes: 5

Views: 339

Answers (3)

potong
potong

Reputation: 58430

This might work for you (GNU sed?):

sed 's/$/p/' file_of_line_numbers | sed -nf - source

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246837

Put the list of line numbers in a separate file, then

gawk 'FNR==NR {line[$1]; next} NR in line' line_numbers file_name

Upvotes: 4

jlliagre
jlliagre

Reputation: 30823

Sed can be more concise:

sed -n "13193p;15791p;16891p" file_name

Upvotes: 9

Related Questions