Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

sed

awk

perl

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?

like image 423
OpenSauce Avatar asked May 11 '11 09:05

OpenSauce


2 Answers

Sed can be more concise:

sed -n "13193p;15791p;16891p" file_name
like image 129
jlliagre Avatar answered Nov 09 '22 17:11

jlliagre


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

gawk 'FNR==NR {line[$1]; next} NR in line' line_numbers file_name
like image 40
glenn jackman Avatar answered Nov 09 '22 19:11

glenn jackman