-4

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.

0

2 Answers 2

7

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! 
Sign up to request clarification or add additional context in comments.

2 Comments

This works for me Ravinder. Thanks.
I'm not the downvoter, but running two command substitutions and comparing their output is a code smell. I would try to refactor it to a more idiomatic flow, perhaps with a single wc or an Awk script.
1

You need to have a space in between your brackets and your comparison expression:

if [ <expression> ]; then echo "Then Do Something"; fi 

So in your case it would be:

if [ "$(wc -l file1.txt)" -eq "$(wc -l file2.txt)" ]; then echo "Warning: No Match!"; fi 

4 Comments

This will give error since ! is present in echo with " and it has a special meaning, when you change " to ' then it should be good.
This answer actually doesn't work because wc -l file1.txt does not return an integer.
Strictly speaking, the double = is also wrong, though Bash allows it.
updated to use -eq

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.