linux - AWK 脚本返回 0 条记录

标签 linux awk gawk

如果我执行

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/

相关文章:

linux - 从本地工作站到远程服务器的代码库复制

linux - 使用通配符排除具有特定后缀的文件

linux - Windows docker 容器与 Linux docker 容器

bash - 将 bash 数组转换为 awk 数组

linux - awk 模式总是匹配最后一条记录?

linux - 从本地 Windows PC 和 Linux 传输数据

linux - 如何使用 unix 删除每个备用数字

linux - 如何用特定列中的字符替换空格?

awk - 如何从日志文件中获取 IP 地址?

linux - 将行转为列,将列转为行