49

How can I list the number of lines in the files in /group/book/four/word, sorted by the number of lines they contain?

The ls -l command lists the files but does not sort them.

1
  • 1
    Do you want the files listed by number of lines, or list the number of lines in the files or both? ls -l doesn't give the number of lines. ls -lS sorts file by size with some ls implementations (size being number of bytes in the content). Nov 27, 2014 at 12:59

6 Answers 6

53

You should use a command like this:

find /group/book/four/word/ -type f -exec wc -l {} + | sort -rn
  • find : search for files on the path you want. If you don't want it recursive, and your find implementation supports it, you should add -maxdepth 1 just before the -exec option.
  • exec : tells the command to execute wc -l on every file.
  • sort -rn : sort the results numerically in reverse order. From greater to lower.

(that assumes file names don't contain newline characters).

4
  • Note that when passed more than one file (or with some implementations, more than one file that it can read), wc will also print a total line, so here you'll also get one or more "total" lines unless there is only one file. You can pipe to grep / to remove them. Feb 28, 2016 at 20:47
  • how can I filter to show only file with X lines minimum (exclude X = 0 line for exemple) ?
    – Matrix
    May 1, 2019 at 15:20
  • 2
    What's the meaning of "+" plus symbol?
    – bob
    Jan 11, 2021 at 6:42
  • @廖茂生: See these answers for the meaning of the plus sign in -exec. May 16 at 14:32
15

Non-recursive

Probably the simplest version if you don't need recursivity :

wc -l /group/book/four/word/*|sort -n

wc counts lines (option -l) in every (but hidden) (*) files under /group/book/four/word/, and sort sorts the result (through the pipe |) numerically (option -n).

Recursive

Someone made a comment to this answer mentioning grep -rlc, before to suppress it. Indeed grep is a great alternative, especially if you need recursivity :

grep -rc '^' /group/book/four/word/|tr ':' ' '|sort -n -k2

will count (option -c) recursively (option -r) lines matching (grep) '^' (that is, beginning of lines) in the directory /group/book/four/word/. Then you have to replace the colon by a space, e.g. using tr, to help sort, which you want to sort numerically (option -n) on the second column (option -k2).

Update : See Stephane's comment about possible limitations and how you can actually get rid of tr.

2
  • 3
    grep -c . counts the lines that contain at least one valid character. Use grep -c '^' to count all the lines (will also count trailing characters after the last newline with some grep implementations). Note that not all grep implementations support a -r and behaviour varies among those that do. You don't need to translate :s (colon, not semicolon) to spaces for sort. Just use -t:. Note that that assumes file names don't contain : or blank or newline characters. Nov 28, 2014 at 18:07
  • 1
    Thanks for posting your non-recursive solution; I didn't know wc gave such a handy total all if you pass multiple paths. Coupling that functionality with the wild card and the pipe to sort is really clean.
    – Qcom
    Sep 25, 2015 at 21:21
8

With zsh:

lines() REPLY=$(wc -l < $REPLY)
print -rC1 /group/book/four/word/*(.no+lines)

We define a new sorting function lines that replies with the number of lines in the file. And we use the o+lines glob qualifier which together with n (for numeric sort), defines how the results of the glob are ordered. (. also added to only check regular files).

That makes no assumption on what character the file names may contain other than hidden files (those starting with .) are omitted. Add the D glob qualifier if you want them as well.

Defining a lines function is useful when you often do something like that, but for a one-off, you could also do it in one go with:

print -rC1 /group/book/four/word/*(.noe['REPLY=$(wc -l < $REPLY)'])

From another shell, simply run:

zsh -c '
  print -rC1 /group/book/four/word/*(.noe['\''REPLY=$(wc -l < $REPLY)'\''])'

Or to store it in a ksh93/bash array if you really had to use those shells:

typeset -a array
eval "
  array=(
    $(
      zsh -c '
        () {
          print -r -- "${(qq)@}"
        } /group/book/four/word/*(N.noe['\''REPLY=$(wc -l < $REPLY)'\''])'
    )
  )
"

(here using proper single-quote quoting (with the qq parameter expansion flag) for the evaluation to be safe).

2
  • 2
    OP is tagged with bash only...
    – l0b0
    Nov 27, 2014 at 13:15
  • 9
    @l0b0 that doesn't mean that the next person who needs this will also be running bash.
    – terdon
    Nov 27, 2014 at 13:40
4

You don't specify whether you also want the files in any subdirectories of /group/book/four/word. The find solution in jherran's answer will descend into subdirectories. If that is not wanted, use the shell instead:

for file in ./*; do [ -f "$file" ] && wc -l "$file"; done | sort -n

If your file names can contain newlines, you can use something like:

for file in ./*; do 
    [ -f "$file" ] && 
        printf "%lu %s\0" "$(wc -l < "$file")" "$file"
done | sort -zn | tr '\0' '\n'

Finally, if you do want to descend into subdirectories, you can use this in bash 4 or above:

shopt -s globstar
for file in ./**/*; do [ -f "$file" ] && wc -l "$file"; done | sort -n

Note that versions of bash prior to 4.3 were following symlinks when recursively descending the directory tree (like zsh's or tcsh's ***/*).

Also, all solutions above will ignore hidden files (those whose name starts with a ., use shopt -s dotglob to include them) and will also include the line count of symbolic links (which the find approach will not).

3
  • Note that other differences from jherran's solution is that yours will also consider symlink to regular files (-xtype f in GNU find or *(-.) in zsh) and will omit hidden files. Nov 27, 2014 at 13:55
  • @StéphaneChazelas thanks, clarified. Why the %lu in printf? As I recall, that means long unsigned decimal, is it really necessary? Why not treat the number as a string? Does it make a difference?
    – terdon
    Nov 27, 2014 at 13:59
  • 2
    If the wc output is empty (for instance because the file is not readable), then that will expand to 0 instead of the empty string, which is slightly better. Some sort implementations work with unsigned integers some with signed. %lu sounds like the safest bet, but it doesn't probably matter as if you have 2^31 lines, that will take ages anyway. Nov 27, 2014 at 14:01
4

If you want to install fd a really fast file finder written in Rust (you should install it, it's great to have anyway)

fd --type=file . | xargs wc -l | sort -n

Basically fd lists the files, xargs will pass the list of files to wc (stands for word count but passing -l will make it count lines) then finally it's sorted from least number of lines to greatest using sort -n.

2
  • this seems like the most intuitive, unixy way to do it. Aug 21, 2021 at 1:09
  • 1
    Add --total=never to wc if you want to process its output, otherwise it will add a line with the total number of lines which might break things
    – piegames
    Jun 18 at 11:45
0

Since the solution provided by @SkippyleGrandGourou didn't work for me, here is my recursive solution using find:

find <folder> -name "<filter>" -exec wc {} \; | sort

Example:

find . -name "*.jsp" -exec wc {} \; | sort

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .