Counting files and directories in Linux

The wc command is one of the GNU coreutils available on Linux. wc is meant to get the amount of newlines, words, bytes and characters in a file. By combining wc with ls or find you can easily get the amount of files or directories in a directory.

Counting all files and directories

We can count all the files and directories in a directory by passing the output of ls to wc using a pipe(|). To list one file per line we use the -1 option for ls.

koen@opensuse:~> ls -1 | wc -l
18

The example above only counts the visible directories and files. In order to include hidden files or directories we have to pass the -a option to the ls command.

koen@opensuse:~> ls -1a | wc -l
24

Count files only

To just count the amount of files we can’t just use the ls command, since it doesn’t make a distinction between files and directories. We can solve this with the find command. The find command is meant to, well.. find directories and files.

The find command looks less straightforward than ls. You need to specify a path, we use . to find in our current working directory. Second we specify the maximum depth find searches, we use 1 as an argument so find will only list the contents of the current directory. To only search for files we have to specify the type f. And finally, to exclude hidden files we filter out files starting with a dot.

To get the amount of files we pipe the output of the find command to wc and we get the amount of files in the current directory.

koen@opensuse:~> find . -maxdepth 1 -type f -name "[!.]*" | wc -l
14

Count directories only

The same trick as the example above can be used to count the directories. We have to change the argument for -type to d and it works.

koen@opensuse:~> find . -maxdepth 1 -type d -name "[!.]*" | wc -l
4

See Also

6 Non-Programming Books for Programmers