且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AWK从文件中每第n行打印一次

更新时间:2022-12-26 20:15:53

您可能要使用:

awk -v patt="$ct" 'NR % patt' results.txt

说明

给出如下文件:

Explanation

Given a file like the following:

$ cat -n a
     1  hello1
     2  hello2
     3  hello3
     4  hello4
     5  hello5
     ...
    37  hello37
    38  hello38
    39  hello39
    40  hello40

这些是等效的:

$ awk 'NR % 7 == 0' a
hello7
hello14
hello21
hello28
hello35
$ ct=7
$ awk -v patt="$ct" 'NR % patt == 0' a
hello7
hello14
hello21
hello28
hello35

甚至

$ awk -v patt="$ct" '!(NR % patt)' a

请注意,语法NR % n == 0表示:行数是n的倍数.如果我们说!(NR % patt),那么只要NR % patt为假,即NRpatt的倍数,就为true.

Note that the syntax NR % n == 0 means: number of line is multiple to n. If we say !(NR % patt), then this is true whenever NR % patt is false, ie, NR is multiple of patt.

在评论时,您使用的是Solaris,而不是默认的awk,请使用以下内容:

As you comment you are using Solaris, instead of default awk use the following:

/usr/xpg4/bin/awk