bash - 在 awk 脚本的 BEGIN 部​​分中确定 NR

标签 bash awk

在 awk 处理输入文件之前,我需要知道预期有多少条记录。

为了确定这一点,我在 awk 脚本的 BEGIN 段中有以下代码....

BEGIN {

    p = ""
    j = 1

    getline             # Activates the FILENAmE variable which normally is not available in the BEGIN section of an awk script.
    n = system("wc -l " FILENAME)       # Assign the result (i.e. number of records in FILENAME) to the n variable.
    gsub(FILENAME, "|", n)      # Remove the input file name appended to the result and replace with "|" just to see what it's done!  
    print n             # See what the hell has happened.

}

我希望看到 n 显示记录数,但我的输出看起来像这样....

12 accounts12
0

“accounts12”是我的输入文件的名称....

最佳答案

system 返回其退出状态(如果成功完成,通常为 0)。所以行:

n = system("wc -l " FILENAME)

将简单地导致 wc 命令的输出像往常一样打印在屏幕上,然后 n 被设置为退出代码 0。

这解释了:

12 accounts12
0

第一行是wc的输出,第二行是n的值。

你可以试试:

BEGIN {
    "wc -l " ARGV[1] | getline n;
    sub(ARGV[1], "|", n);
    print n;
}

这应该得到你的n。它的好处是不会占用文件的第一行。

关于bash - 在 awk 脚本的 BEGIN 部​​分中确定 NR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583580/

相关文章:

java - 如何制作 bash 包装脚本来执行接受 stdin 并输出到 stdout 的 java jar

regex - Bash:重新定位字符串中的子字符串

Linux Awk 代码帮助

linux - 从行列表中打印行号之间的行,并使用 GNU Parallel 将每个实例保存在单独的文件中

linux - 如何将 top 命令与日期列结合起来

bash - 在 HISTIGNORE 中忽略 'history numlines' 的模式,bash

Bash 在匹配组上查找/替换和运行命令

bash - 针对各种 CRL 文件验证 SSL 证书

Linux - 在 awk 中读取数组

linux - 字符串校验和