How to print every nth line in a file in Linux?

H
ow to print every nth line of a file? The requirement is to print every 3rd line of the file.

Let us consider a file with the following content.

$ cat file
AIX
Solaris
Unix
Linux
HPUX
Ubuntu

1. Using awk
:

$ awk '!(NR%3)' file
Unix
Ubuntu

NR variable contains the line number of the file in awk. If NR modulus 3 is equal to 0, it indicates the line is a multiple of 3. And only those lines are printed which modulus is 0.

2. Using sed
:

$ sed -n 'n;n;p;' file
Unix
Ubuntu

n command in sed prints the current line(if -n is not present) and reads the next line in the buffer. Since -n switch is present, the n command does not print. Hence, after the ‘n;n;’, the 3rd line is present in the pattern space and it is printed using the p command. And this repeats till the end of the file, and hence every 3rd line gets printed.

3. Using Perl
:

$ perl -lne '$.%3 or print;' file
Unix
Ubuntu

This is same as awk solution. The $. variable in Perl is equivalent to awk’s NR. Only those lines are printed whose modulus is not equal to 0.

4. Bash shell script
:

#!/usr/bin/bash

x=0
while read line
do
   ((x++))
   [ $x -eq 3 ] && { echo $line ; x=0;}
done < file
责编内容来自:The UNIX School (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » How to print every nth line in a file in Linux?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录