2

我正在阅读 The UNIX Programming Environment 和第 4.4 节,关于 awk,有这个示例代码:

    awk '
    FILENAME != prevfile {   # new file
        NR = 1               # reset line number
        prevfile = FILENAME
    }
    NF > 0 {
        if ($1 == lastword)
            printf "double %s, file %s, line %d\n",$1,FILENAME,NR
        for (i = 2; i <= NF; i++)
            if ($i == $(i-1))
                printf "double %s, file %s, line %d\n",$i,FILENAME,NR
        if (NF > 0)
            lastword = $NF
    }' $*

为什么在已经有 NF > 0 作为模式的块内测试 NF > 0?

4

2 回答 2

3

包含在本书的勘误注释中:

Page 121, first program: test "if (NF > 0)" is unnecessary.

所以这是出版商和/或文案编辑犯的错误。

于 2012-10-08T04:21:26.520 回答
1

NF > 0 用于检查此行中是否有任何字段,因为 NF 可能为 0。

我给你举个例子:

awk '{print "hello";}' -
1
hello

hello

当我写“1”时,块被执行(打印“hello”),当我输入一个空行时我再次被执行(第二个“hello”)

如果我将代码更改为:

awk 'NF > 0 {print "hello";}' -
1
hello

当输入为空行时,它不会显示第二个“hello”,因为 NF 为 0。

于 2012-09-04T14:27:33.757 回答