Elegant Solutions: File and Directory Count
How do you count the number of files in a particular directory? If your first instinct is to use “ls -l | wc -l
”, that will only get you the total number of lines in the list, which will include directories and will count the first line of the output of ls -l
which is the total
number of 512-byte blocks used in the directory. (Read your man pages!)
Because the ls -l
outputs one row per file/directory and starts with the POSIX permissions block (that is “drwxrwxrwx
” for a directory and “-rwxrwxrwx
” for a file) we can use grep -c
to count them. The -c
flag causes grep
to return the count of matches as opposed to the matched content.
Since “-
” is the first character in a line representing a file:
$ ls -l | grep -c '^-'
2
and of course, to count the number of directories it is:
$ ls -l | grep -c '^d'
If you want to see what those files or directories are, just drop the -c
:
$ ls -l | grep '^-'
-rwxrwxrwx@ 1 bowman staff 107115 26 Jan 11:59 DSCF5245 400x514.JPG*
-rwxrwxrwx@ 1 bowman staff 1414006 19 Jan 11:18 DSCF5245.JPG*
Also, remember if you want to include dot (.
) files, you have to use the -a
flag in ls
, i.e.
ls -la | grep -c '^-'
Now, if you know your globbing, there are other ways to achieve the above. Just bear in mind that globbing is shell specific.
For instance, in zsh
with extended globbing enabled, you can list the “plain” files in a directory with ls *(.)
. So you could count all the files with:
% ls *(.) | wc -l
But that, really, is another whole topic…