Search code examples
linuxcygwinwc

comparing line count in multiple text files


I have multiple text files in a directory and want to compare line count for each file against each other.

Below is my code but the output is incorrect; it's always showing me "bigger" whatever the line count.

for f in *.txt; do
for f2 in *.txt; do
if [ "wc -l $f" > "wc -l $f2" ]; then 
echo bigger;
fi;
done;done

I'm not sure if this part if [ "wc -l $f" > "wc -l $f2" ] is correct.


Solution

  • Double quotes introduce a string, they don't run the enclosed command. > in [ ... ] compares strings, not numbers, and needs to be backslashed, otherwise it's interpreted as a redirection. Moreover, what output do you expect when the files are of the same size (e.g. when $f == $f1)?

    #!/bin/bash
    for f in *.txt; do
        size_f=$(wc -l < "$f")
        for f2 in *.txt; do
            size_f2=$(wc -l < "$f2")
    
            if (( size_f > size_f2 )) ; then
                echo "$f" bigger than "$f2"
            elif (( size_f == size_f2 )) ; then
                echo "$f" same size as "$f2"
            else
                echo "$f" smaller than "$f2"
            fi
        done
    done