1

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
  • 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, 2014 at 17:57

5 Answers 5

6

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.

1
5

You should use wc:

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

From man wc:

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

SYNOPSIS
       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.

2
  • 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, 2014 at 14:51
  • @Dubu: Yes, we all know that according to man wc.
    – cuonglm
    Jun 16, 2014 at 14:54
4

you can pipe your command to wc command:

ls -l | wc -l
2

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).

1

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\}/\|^$'

or...

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

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

You must log in to answer this question.

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