AWK 脚本 returns 0 条记录

AWK script returns 0 records

如果我执行

echo "abcd" | awk '{print NR}'

returns1个,不错

但是如果我创建一个脚本文件script.awk,其内容为:

BEGIN{print NR}

并执行

echo "abcd" | awk -f script.awk

returns 0.

为什么?

您正在检查 BEGIN 块中的记录数,这是行不通的。

为什么?因为在 BEGIN 块中,文件尚未加载,标准输入也未加载。

相反,将其打印在 END 块中。

$ cat a.wk                 
END {print NR}
$ echo "abcd" | awk -f a.wk
1

来自man awk

Gawk executes AWK programs in the following order. First, all variable assignments specified via the -v option are performed. Next, gawk compiles the program into an internal form. Then, gawk executes the code in the BEGIN rule(s) (if any), and then proceeds to read each file named in the ARGV array (up to ARGV[ARGC]). If there are no files named on the command line, gawk reads the standard input.

awk 程序遵循此方案:

CONDITION { ACTION(S) } NEXT_CONDITION { ACTION(s) }

可以省略ACTION(S)。在这种情况下 awk 将简单地打印当前记录。

BEGIN 只是一个特殊条件,在 之前 awk 开始读取输入。仅供参考,还有一个 END 条件为真 awk 处理了所有输入行之后。

命令行脚本和放入文件的脚本的语法没有区别。


结论:

您可以简单地将其放入您的脚本中:

test.awk

{print NR}

并这样称呼它:

awk -f test.awk <<< 'hello'