Counting number of files in a directory with an OSX terminal command

The fastest way to obtain the number of files within a directory is by obtaining the value of that directory's kMDItemFSNodeCount metadata attribute.

mdls -name kMDItemFSNodeCount directory_name -raw|xargs

The above command has a major advantage over find . -type f | wc -l in that it returns the count almost instantly, even for directories which contain millions of files.

Please note that the command obtains the number of files, not just regular files.


I don't understand why folks are using 'find' because for me it's a lot easier to just pipe in 'ls' like so:

ls *.png | wc -l

to find the number of png images in the current directory.


You seem to have the right idea. I'd use -type f to find only files:

$ find some_directory -type f | wc -l

If you only want files directly under this directory and not to search recursively through subdirectories, you could add the -maxdepth flag:

$ find some_directory -maxdepth 1 -type f | wc -l

Open the terminal and switch to the location of the directory.

Type in:

find . -type f | wc -l

This searches inside the current directory (that's what the . stands for) for all files, and counts them.

Tags:

Linux

Macos

Shell