1,A
2,B
3,C
4,D
5,E
6,F
7,G
8,H
9,I
10,J
11,K
12,L
13,M
14,N
How do I print row 4 first and then the 9th row and then the 14th row using awk? I want to first print the 4th row and then continue printing every 5th row after the 4th row, until the end of the file.
I tried this:
awk '{if(NR==4 || (NR>4 && NR==NR+7)) print $0}' file
But this doesn’t work. Any help is appreciated.
The output should be:
4,D
9,I
14,N
>Solution :
Assuming you want to print every 5th line starting from a specific line number:
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
c && !((++c) % 5) says:
If
cis set then incrementcand test if that new value modulo
5is zero.
So no line before NR==4 can be printed as c is never populated before that happens, and then when c is set to 4, it’s then increment to 5 and 5 % 5 is 0 so the line is printed. c gets incremented for every line after that and so c % 5 continually rotates through 1 2 3 4 0 thus printing every 5th line when 0 occurs and so !0 is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19