I need to count the number of lines in x files and compare which has more.

The one I've done only takes two files and compares them. Any idea how to make it x amount of files?

echo Enter the filename read fn

echo Enter another file read fn1

for WORD in $(cat $fn) do
        echo "$WORD" done | wc -l

for WORD in $(cat $fn1) do
        echo "$WORD" done | wc -l

if (cat $fn | wc -l > cat $fn1 | wc -l) then
        echo First file has more lines than second file else if (cat $fn1 | wc -l > cat $fn | wc -l) then
        echo Second file has more lines than first file.

  • 1
    I suggest you use wc -l $fn instead of cat $fn | wc -l, in order to avoid a UUoC
    – rahmu
    Feb 26, 2012 at 23:03

4 Answers 4

find . -name "*.txt" -exec wc -l '{}' \; | sort -n

you can learn line size then sort them with a one liner.

  • can you explain what this actually does? Apr 25, 2015 at 9:25
wc -l * | head -n -1 | sort | tail -1 | cut -d ' ' -f 3

This will give you the filename of the file with the highest number of lines

  • won't this break if there's a newline in the filename?
    – rahmu
    Feb 26, 2012 at 23:01
  • @rahmu newlines are the least expected in filenames, moreover I don't know if it's even possible to create a filename with a newline character in it. Feb 27, 2012 at 13:26

Just name all files you want to compare, and sort by size (-numeric):

wc -l a.html b.html c.html | sort -n
find . -name '*txt' | xargs wc -l | sort -n

On my machine, this was faster than the -exec version.