在 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/