e1v1s
e1v1s

Reputation: 385

How to use awk to print +3 lines of every nth line starting at a specific line?

So starting at line 2 I want to print the following 3 lines and do the same thing for every 16th line until the end of my file. All I have so far is:

    awk 'NR % 16 ==2' 

I'm having trouble in adding the "print the following 3 lines" part. Any suggestions?

Upvotes: 0

Views: 1228

Answers (4)

karakfa
karakfa

Reputation: 67467

with smart counters..

$ awk 'NR%16==2{c=4} c&&c--' <(seq 40)
2
3
4
5
18
19
20
21
34
35
36
37

Upvotes: 6

hek2mgl
hek2mgl

Reputation: 157947

That should work:

awk 'NR>=2 && !((NR-2)%16) {print; getline; print; getline; print}' file

Upvotes: 1

Ren
Ren

Reputation: 2946

Try this:

$ awk 'BEGIN{flag=0;count=0}NR%16==2{flag=1;print;next}flag{print;++count}count==3{count=0;flag=0}' <filename>

Example

input.txt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Use:

$ awk 'BEGIN{flag=0;count=0}NR%16==2{flag=1;print;next}flag{print;++count}count==3{count=0;flag=0}' input.txt

Output:

2
3
4
5
18
19
20
21

Upvotes: 0

sat
sat

Reputation: 14949

You can try this sed:

sed -n '2~16{N;N;N;p}' file

Upvotes: 1

Related Questions