Robert Buckley Robert Buckley - 6 months ago 17
Linux Question

Recursively counting files in a Linux directory

How can I recursively count files in a Linux directory?

I found this:

find DIR_NAME -type f ¦ wc -l


But when I run this it returns the following error.


find: paths must precede expression: ¦

Answer

This should work:

find DIR_NAME -type f | wc -l

Explanation:

  • -type f to include only files.
  • | redirects find command's standard output to wc command's standard input.
  • wc (short for word count) counts newlines, words and bytes on its input (docs).
  • -l to count just newlines.

Notes:

  • Replace DIR_NAME with . to execute the command in the current folder.
  • You can also remove the -type f to include directories (and symlinks) in the count.
  • It's possible this command will overcount if filenames can contain newline characters.
Comments