How to compare number of lines of two files using Awk

≯℡__Kan透↙ 提交于 2019-12-25 04:44:13

问题


I am new to awk and need to compare the number of lines of two files. The script shall return true,

if lines(f1) == (lines(f2)+1)

otherwise false. How can I do that?

Best regards


回答1:


If it has to be awk:

awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' file1 file2

The varibale x is incremented and contains the number of line of file1 and FNR contains the number of file2. At the end, both are compared and the script is exited 0 or 1.

See an example:

user@host:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' shortfile longfile
user@host:~$ echo $?
1
user@host:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' samefile samefile
user@host:~$ echo $?
0



回答2:


Something like this should suit your purposes:

 [ oele3110 $] cat line_compare.awk
#!/usr/bin/gawk -f

NR==FNR{
    n_file1++;
}
NR!=FNR{
    n_file2++;
}

END{
    n_file2++;
    if(n_file1==n_file2){exit(1);}
}
 [ oele3110 $] cat f1
1
1
1
1
1
1
 [ oele3110 $] cat f2
1
1
1
1
1
 [ oele3110 $] cat f3
1
1
1
1
1
 [ oele3110 $]
 [ oele3110 $] wc -l f*
 6 f1
 5 f2
 5 f3
16 total
 [ oele3110 $] ./line_compare.awk f1 f2
 [ oele3110 $] echo $?
1
 [ oele3110 $] ./line_compare.awk  f2 f3
 [ oele3110 $] echo $?
0
 [ oele3110 $]

Actually, I think I should have asked you to invest a bit more effort before giving you the answer. I'll leave it for now, but next time I won't make the same mistake.



来源:https://stackoverflow.com/questions/28452247/how-to-compare-number-of-lines-of-two-files-using-awk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!