我正在尝试编写一个 awk 脚本,并且在完成任何操作之前告诉用户文件中有多少行。我知道如何在 END 部分执行此操作,但无法在 BEGIN 部分执行此操作。我搜索了 SE 和 Google,但只在 END 部分或作为 bash 脚本的一部分找到了六种方法来执行此操作,而不是在任何处理发生之前如何执行此操作。我希望得到类似以下的内容:
#!/usr/bin/awk -f
BEGIN{
print "There are a total of " **TOTAL LINES** " lines in this file.\n"
}
{
if($0==4587){print "Found record on line number "NR; exit 0;}
}
但一直无法确定如何做到这一点,如果可能的话。谢谢。
最佳答案
您可以读取文件两次:
awk 'NR!=1 && FNR==1 {print NR-1} <some more code here>' file{,}
在你的例子中:
awk 'NR!=1 && FNR==1 {print "There are a total of "NR-1" lines in this file.\n"} $0==4587 {print "Found record on line number "NR; exit 0;}' file{,}
您可以使用 file file
代替 file{,}
(它只会让它显示两次)
NR!=1 && FNR==1
这仅在第二个文件的第一行是正确的。
使用 awk
脚本包含:
#!/usr/bin/awk -f
NR!=1 && FNR==1 {
print "There are a total of "NR-1" lines in this file.\n"
}
$0==4587 {
print "Found record on line number "NR; exit 0
}
调用:
awk -f myscript file{,}
关于text - 使用 `awk` 在 BEGIN 部分打印文件中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29314555/