如何打印3号倍数的文件行,如第3行,第6行,第9行等

ram*_*mee 2 unix

我有一个文件,我只想要3的倍数的行.是否有任何UNIX命令来执行此任务?

fed*_*qui 7

这使它:

awk 'NR%3==0' file
Run Code Online (Sandbox Code Playgroud)

NR代表记录的数量,在这种情况下是行数.因此条件是"(线数/ 3)具有模数0"==="线是3"的倍数.

测试

$ cat file
hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
hello10
$ awk 'NR%3==0' file
hello3
hello6
hello9
Run Code Online (Sandbox Code Playgroud)


Zer*_*eus 5

使用 GNU sed:

sed -n 0~3p filename
Run Code Online (Sandbox Code Playgroud)

您可以通过更改 之前的数字从不同的行~开始,因此要从第一行开始,它将是:

sed -n 1~3p filename
Run Code Online (Sandbox Code Playgroud)

例子:

$ 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
Run Code Online (Sandbox Code Playgroud)

或者,使用像 BSD sed 这样的非 GNU sed:

$ sed -n '3,${p;n;n;}' filename 
The third line
The sixth line
Run Code Online (Sandbox Code Playgroud)