Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a range of line every nth interval using awk, sed, or other unix command?

Tags:

unix

sed

awk

cat

I know how to get a range of lines by using awk and sed. I also do know how to print out every nth line using awk and sed.

However, I don't know how to combined the two.

For example, I have a file with 1780000 lines.

For every 17800th line, I would like to print 17800th line plus the two after that.

So if I have a file with 1780000 lines and it starts from 1 and ends at 1780000, this will print:

1
2
3
17800
17801
17802
35600
35601
35602
# ... and so on.

Does anyone know how to get a range of line every nth interval using awk, sed, or other unix command?

like image 321
Jamie Johnson Avatar asked Apr 22 '13 00:04

Jamie Johnson


People also ask

Which is faster awk or sed?

Generally I would say grep is the fastest one, sed is the slowest. Of course this depends on what are you doing exactly. I find awk much faster than sed . You can speed up grep if you don't need real regular expressions but only simple fixed strings (option -F).

How do I print a specific line in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


1 Answers

Using GNU sed:

sed -n '0~17800{N;N;p}' input

Meaning,

For every 17800th line: 0~17800
  Read two lines: {N;N;
  And print these out: p}

We can also add the first three lines:

sed -n -e '1,3p' -e '0~17800{N;N;p}' input

Using Awk, this would be simpler:

awk 'NR%17800<3 || NR==3 {print}' input
like image 185
perreal Avatar answered Oct 28 '22 09:10

perreal