0

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

jww
  • 97,681
  • 90
  • 411
  • 885
oele3110
  • 5
  • 2
  • 1
    Normally you would use `wc -l` to count the lines in a file... failing that, have a look at Ed's answer here to see how to process 2 files http://stackoverflow.com/questions/21280959/using-awk-to-process-two-different-files-consecutively – Mark Setchell Feb 11 '15 at 10:51

2 Answers2

3

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
chaos
  • 8,162
  • 3
  • 33
  • 40
  • :-) Very succinct - have a vote. Actually, `awk` will exit with status zero naturally, so if you invert the logic and exit with status 1, you can omit the `exit 0`. – Mark Setchell Feb 11 '15 at 13:07
  • You could even just do `END{exit (x!=FNR)}` but maybe that's getting too obfuscated. – Ed Morton Feb 11 '15 at 21:07
  • I think the required functionality is to return 1 when one file contains one more line than the other, not when both files contain the same number of lines, isn't it? – user3065349 Feb 12 '15 at 14:14
0

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.

user3065349
  • 171
  • 5