Dyl*_*lan 3 awk text text-processing
我正在尝试编写一个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;}
}
Run Code Online (Sandbox Code Playgroud)
但是如果有可能的话,一直无法确定如何做到这一点.谢谢.
您可以阅读该文件两次.
awk 'NR!=1 && FNR==1 {print NR-1} <some more code here>' file{,}
Run Code Online (Sandbox Code Playgroud)
在你的例子中:
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{,}
Run Code Online (Sandbox Code Playgroud)
您可以使用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
}
Run Code Online (Sandbox Code Playgroud)
awk -f myscript file{,}
Run Code Online (Sandbox Code Playgroud)