How can I get a count of files in a directory using the command line?
I have a directory with a large number of files. I don't see a
lsswitch to provide the count. Is there some command line magic to get a count of files?
Using a broad definition of "file"
ls | wc -l
(note that it doesn't count hidden files and assumes that file names don't contain newline characters).
To include hidden files (except
..) and avoid problems with newline characters, the canonical way is:
find . ! -name . -prune -print | grep -c /
find .//. ! -name . -print | grep -c //
`wc` is a "word count" program. The `-l` switch causes it to count lines. In this case, it's counting the lines in the output from `ls`. This is the always the way I was taught to get a file count for a given directory, too.
that doesn't get everything in a directory - you've missed dot files, and collect a couple extra lines, too. An empty directory will still return 1 line. And if you call `ls -la`, you will get three lines in the directory. You want `ls -lA | wc -l` to skip the `.` and `..` entries. You'll still be off-by-one, however.
If you have a file whose name contains a newline, this approach will incorrectly count it twice.
A corrected approach, that would not double count files with newlines in the name, would be this: `ls -q | wc -l` - though note that hidden files will still not be counted by this approach, and that directories will be counted.
How does this work? I need to know how to modify it slightly / combine recursion with including hidden files. Even a link would be nice.