如果我执行
echo "abcd" | awk '{print NR}'
返回 1,这很好。
但是如果我创建一个脚本文件script.awk
,内容如下:
BEGIN{print NR}
并执行
echo "abcd" | awk -f script.awk
返回 0。
为什么?
最佳答案
您正在检查 BEGIN
block 中的记录数,但这是行不通的。
为什么?因为在 BEGIN
block 中,文件还没有加载,标准输入也没有。
相反,将其打印在 END
block 中。
$ 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.
关于linux - AWK 脚本返回 0 条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652979/