Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

migrated from programmers.stackexchange.com Feb 26 '12 at 20:25

This question came from our site for professional programmers interested in conceptual questions about software development.

I suggest you use wc -l $fn instead of cat $fn | wc -l, in order to avoid a UUoC – rahmu Feb 26 '12 at 23:03
find . -name "*.txt" -exec wc -l '{}' \; | sort -n

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

share|improve this answer
can you explain what this actually does? – s.matthew.english Apr 25 '15 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

share|improve this answer
won't this break if there's a newline in the filename? – rahmu Feb 26 '12 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. – Khaja Minhajuddin Feb 27 '12 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
share|improve this answer
find . -name '*txt' | xargs wc -l | sort -n

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.