Search code examples
awktext-processingline-count

How to compare number of lines of two files using Awk


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


Solution

  • 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