Reputation: 47
I have a file and I want only lines that are multiples of 3. Is there any UNIX command to perform this task?
Upvotes: 2
Views: 2108
Reputation: 59168
With GNU sed:
sed -n 0~3p filename
You can start at a different line by changing the number before the ~
, so to start with the first line instead, it'd be:
sed -n 1~3p filename
Example:
$ cat filename
The first line
The second line
The third line
The fourth line
The fifth line
The sixth line
The seventh line
$ sed -n 0~3p filename
The third line
The sixth line
$ sed -n 1~3p filename
The first line
The fourth line
The seventh line
Alternatively, with a non-GNU sed like BSD sed:
$ sed -n '3,${p;n;n;}' filename
The third line
The sixth line
Upvotes: 5
Reputation: 290035
This makes it:
awk 'NR%3==0' file
NR
stands for number of record, which in this case is number of line. So the condition is "(number of line / 3) having modulus 0" === "lines that are multiple of 3".
$ cat file
hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
hello10
$ awk 'NR%3==0' file
hello3
hello6
hello9
Upvotes: 7