Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of files in a directory

Is there any method in Linux to calculate the number of files in a directory (that is, immediate children) in O(1) (independently of the number of files) without having to list the directory first? If not O(1), is there a reasonably efficient way?

I'm searching for an alternative to ls | wc -l.

like image 287
yassin Avatar asked Sep 13 '10 15:09

yassin


People also ask

How do you get files count in a directory in Linux?

The easiest way to count files in a directory on Linux is to use the “ls” command and pipe it with the “wc -l” command. The “wc” command is used on Linux in order to print the bytes, characters or newlines count.

How do I count the number of files in a directory in PowerShell?

To get count files in the folder using PowerShell, Use the Get-ChildItem command to get total files in directory and use measure-object to get count files in a folder.


1 Answers

readdir is not as expensive as you may think. The knack is avoid stat'ing each file, and (optionally) sorting the output of ls.

/bin/ls -1U | wc -l

avoids aliases in your shell, doesn't sort the output, and lists 1 file-per-line (not strictly necessary when piping the output into wc).

The original question can be rephrased as "does the data structure of a directory store a count of the number of entries?", to which the answer is no. There isn't a more efficient way of counting files than readdir(2)/getdents(2).

like image 90
PhilR Avatar answered Sep 29 '22 07:09

PhilR