-2

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.

user2334436
  • 949
  • 5
  • 13
  • 34

2 Answers2

0

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
choroba
  • 231,213
  • 25
  • 204
  • 289
0

Here is what you want:

#!/bin/bash

N=0
M=0
for line in $( find . -type f -name \*.sh ); do
    N=$( wc -l ${line} | cut -d" " -f1 )
    FILE=$( wc -l ${line} | cut -d" " -f2 )
    if [[ ${M} < ${N} ]]; then
        M=${N}
        BIGFILE=${FILE}
        echo "GOTCHA : ${M}"
    fi
done
echo "BIG FILE: ${BIGFILE} ( ${M} lines )"
Craft
  • 1
  • 1