I am trying to compare command outputs between two servers. I want to find out the number of lines from the output of commands such as ls -l. Is there a way to do so? So far I have not found anything.

  • 1
    Depends on what you are compairing. diff /dir1 /dir2 will show the differneces. If there is no output they are the same – Panther Jun 16 '14 at 17:57

For someone this may be easier to remember:

ls -l | grep . -c

Please note both grep and wc will count auxiliary lines like total 32044 or or ./dirname:. To avoid this especially in recursive output like ls -lR try this:

find . -type f | grep . -c

where first . is the directory path and -type f means that find will list files only. If you need all types (including directories, sockets etc) then just omit -type f.

Please note: wc -l DOES count empty lines (just '\n') whilst grep . -c - does NOT.

  • 2
    grep -c '^' counts empty lines. – Gilles Jun 16 '14 at 22:57

You should use wc:

$ wc -l .emacs.d/init.el 
73 .emacs.d/init.el

From man wc:

       wc - print newline, word, and byte counts for each file

       wc [OPTION]... [FILE]...
       wc [OPTION]... --files0-from=F
       -l, --lines
              print the newline counts

wc is part of GNU coreutils, you can have it in most Unix-like system.

  • Note that wc -l really counts newline characters, as the manpage says! If your input doesn't end in a newline, the last line will not count. Example (echo from bash suppresses the trailing newline with -n): echo -n "foobar" | wc -l results in 0. – Dubu Jun 16 '14 at 14:51
  • @Dubu: Yes, we all know that according to man wc. – cuonglm Jun 16 '14 at 14:54

you can pipe your command to wc command:

ls -l | wc -l

Yep, you could find number of lines from the output of ls -l through awk command also,

ls -l | awk 'END{print NR}'

Awk's NR variable stores the last record number at the end(After reading all the input lines).


If you want to compare a count of the files processed by either server then you can do that reliably like:

ls -aR1qp ./ | grep -cv '/\|^$'

That recursively lists all files - not directories - one per line including .dotfiles beneath the current directory using shell globs as necessary to replace non-printable characters. grep filters out any parent directory listings or .. or */ or blank lines - so there should only be one line per file - the total count of which grep returns to you. If you want child directories included as well do:

ls -aR1qp ./ | grep -cv '^\.\{1,2\}/\|^$'


ls -AR1q ./ | grep -cv '/\|^$'

Note that the -A option to ls is POSIX as of the latest version.

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.