9

I have a large file and I would like print from each sequential 50 lines , the 15th and 25th lines.

sed -n '15,25p' inputfile

How to modify this command to print only lines 15 and 25 and to loop over each 50 lines in the file.

4

Another approach using awk, based on Sundeep's idea of using a list:

awk 'BEGIN { a[15] a[25] }; NR % 50 in a'

Set keys in the array a based on the lines you want to print. Print lines where NR % 50 matches one of the keys in the array.


To give some indication of the performance, I timed this approach and compared with the other answers, taking an average of the user time for 3 runs.

0.276s

$ time awk 'BEGIN { a[15] a[25] }; NR % 50 in a' <(seq 1000000) > /dev/null

0.374s

$ time awk 'NR % 50 == 15 || NR % 50 == 25' <(seq 1000000) > /dev/null

0.384s

$ time perl -ne 'print if $.%50==15 || $.%50==25' <(seq 1000000) > /dev/null

0.542s

$ time perl -ne 'print if grep {$_==$.%50} (15,25)' <(seq 1000000) > /dev/null
22
awk 'NR % 50 == 15 || NR % 50 == 25'

would be the obvious portable way.

Note a GNU sed alternative:

sed '15~50b;25~50b;d'

With any sed, you can always do:

sed -n 'n;n;n;n;n;n;n;n;n;n;n;n;n;n;p;n;n;n;n;n;n;n;n;n;n;p;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n'

(get next line 14 times, print, next line 10 times, print, next line 25 times, back to the next cycle (which grabs the missing extra line to make 50)).

9

With perl

1) Similar to the awk solution, $. variable stores line number

$ seq 135 | perl -ne 'print if $.%50==15 || $.%50==25'
15
25
65
75
115
125

2) Check against list of line numbers, easier to extend

$ seq 135 | perl -ne 'print if grep {$_==$.%50} (15,25)'
15
25
65
75
115
125

$ seq 135 | perl -ne 'print if grep {$_==$.%50} (15,25,32)'
15
25
32
65
75
82
115
125
132
10

this is a job for awk

awk '(NR%50==15) || (NR%50==25)' inputfile

edit: I was mislead by sed instruction in OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.