Reputation: 5044
I have this
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
line14
line15
My aim is to have
line1
line3
line4
line6
line7
line9
line10
line12
line13
line15
I tried the code below this but it is not doing what I want. i'm not sure what I'm doing wrong.
awk 'NR == 1 || NR % 3 != 0' file
Any clues on the why?
Upvotes: 3
Views: 4246
Reputation: 18807
You can just use GNU sed:
sed -i '2~3d' test.txt
You can also remove the -i
in case you would not want to save the result.
Extract for sed man page:
first~step Match every step'th line starting with line first. For example,
sed -n 1~2p
will print all the odd-numbered lines in the input stream, and the address2~5
will match every fifth line, starting with the second.
Upvotes: 8
Reputation: 47089
Here is one way of doing it with portable sed
.
To delete every 3rd line:
sed 'n; n; d' infile
To delete every 3rd line, starting with line 2:
sed '1n; 2d; n; n; d' infile
Output:
line1
line3
line4
line6
line7
line9
line10
line12
line13
line15
Upvotes: 2
Reputation: 4371
You had the right idea using % 3
- just off by one since you want to remove starting at line 2 rather than 3. The test for NR == 1
is superfluous, falling within the modulus test, but it wasn't causing any trouble:
$ awk '(NR+1) % 3' file
line1
line3
line4
line6
line7
line9
line10
line12
line13
line15
Upvotes: 8
Reputation: 44023
To ignore the lines like in your example output, use
awk 'NR % 3 != 2' file
Upvotes: 3
Reputation: 784898
You can use:
awk '(NR+1)%3' file
line1
line3
line4
line6
line7
line9
line10
line12
line13
line15
This will skip every 3rd line starting from line #2. So line # 2, 5, 8, 11, 14 will be skipped.
Upvotes: 2