I would like to compare the line counts of two separate files. While I have tried using wc -l
in the comparison, I'm struggling to get it working properly.
I have:
if [ "$(wc -l file1.txt)" == "$(wc -l file2.txt)" ]; then echo "Warning: No Match!"; fi
However, the if/then statement does not return the correct output.
If file 1 and 2 have the same number of lines, what is the proper way of writing this code?
File1.txt:
example1
example2
example3
File2.txt:
example4
example5
example6
Update: We found that the wc -l
command must return a digit only for the comparison. Unlike the question Why should there be a space after '[' and before ']' in Bash?, this question requires using wc -l
to get an integer that can be compared the number of lines in separate files.
Could you please try following and let me know if this helps you.
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
Examples for above code: Let's say we have following Input_files:
cat file1.txt
I
am
Cookie
cat file2.txt
I
am
Cookie
Now since we could see number of lines are not equal in both the files so following result will come.
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
Warning: No Match!
Now if we make both the file's lines equal now as follows.
cat file1.txt
I
am
Cookie
cat file2.txt
I
am
Cookie
Now when we run same code it will give as follows.
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
Match!