I am trying to get x amount of file names printed from highest line count to lowest. ATM i have this

wc -l /etc/*.conf |sort -rn | head -6 | tail -5 |

and i get this

  543 /etc/ltrace.conf
  523 /etc/sensors3.conf
  187 /etc/pnm2ppa.conf
  144 /etc/ca-certificates.conf

Now this would be ok but i only need the names, is there any way of removing the number of lines?

  • tag a cut -c7- on the end ? – steve Dec 2 '19 at 22:37
  • With zsh: print -rC1 -- /etc/*.conf(.NOe:'REPLY=$(wc -l <$REPLY)':[1,5]) (for the five longest files). – Kusalananda Dec 3 '19 at 15:48

An alternative:

wc -l /etc/*.conf |sort -rn | head -6 | tail -5 | tr -s ' ' | cut -d' ' -f3

Another golf variation.

wc -l /etc/*.conf | sort -rn | sed -n '2,5s/^ *[1-9][0-9]* //p'

The sed takes lines 2-5 (line 1 being the grand total, since we have reversed the output line order) and removes the leading "{space} {number} {space}" pattern.

(In common with every other solution so far, this pipeline is not robust when given a filename that contains a newline.)


Last head + tail can be replaced with single awk expression that will print only top 5 filenames:

wc -l /etc/*.conf | sort -rn | awk 'NR>1{ $1=""; print $0 }NR==6{ exit }'

I would use a simple perl script that does the work for you:

  1. you pass in the number of files you want and a list of files to process
  2. it computes the line counts and stores the results in an associative array
  3. it sorts the array by value and prints the number of files

There's no error-checking in the script (e.g. that "N" is sane; there's a non-empty list of files; an "N" not greater than the number of files; that the files are regular files and not directories, sockets, etc).


# prints the top N given files by line count

my $n = shift;
my %counts = ();
foreach my $file (@ARGV) {
  chomp($counts{$file} = `wc -l < "$file"`);

foreach my $file (sort { $counts{$b} <=> $counts{$a} } keys %counts) {
  print "$file\n";
  last unless --$n;

This direction is easier than trying to sort values in shell arrays or than relying on filenames to omit certain characters. The perl script's output is potentially ambiguous if your filenames contain newlines; if you were going to do further work with the files, I would do that work inside the perl script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.