How to get n lines for every m lines (n

sedtext processing

Is there a very simple way (maybe using one line with sed?) to get n lines, starting at ath line within this chunk of n lines, for every m lines?

More specifically, I have a file with millions of lines. For every 4 lines, I want to get the first two lines.

But I guess I also want to get an idea of doing this in other similar situations. That's why I asked a more general question here.

Best Answer

With gnu split:

n=2
m=4 
split -l ${m} --filter="head -n ${n}" infile

and if you wanted to do it only after the ith line, just redirect the previous lines to /dev/null:

n=2
m=4 
i=7
{ head -n ${i} >/dev/null; split -l ${m} --filter="head -n ${n}"; } <infile

If you don't have access to gnu tools you could use awk:

awk -vn=2 -vm=4 -vi=7 'NR<=i{next}; (NR-i)%m==1{c=1}; c++<=n' infile
Related Question