-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.

DomainsFeatured
  • 1,426
  • 1
  • 21
  • 39

2 Answers2

6

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!
codeforester
  • 39,467
  • 16
  • 112
  • 140
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • This works for me Ravinder. Thanks. – DomainsFeatured Oct 11 '17 at 02:33
  • 1
    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. – tripleee Oct 11 '17 at 04:11
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
hackerrdave
  • 6,486
  • 1
  • 25
  • 29