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 ls switch to provide the count. Is there some command line magic to get a count of files?

    `tree . | tail` or `tree -a . | tail` to include hidden files/dirs, `tree` is recursive if that's what you want.

  • James Roth

    James Roth Correct answer

    10 years ago

    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 ..) and avoid problems with newline characters, the canonical way is:

    find . ! -name . -prune -print | grep -c /
    

    Or recursively:

    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.

    please add note that `ls` does `ls -1` if the output is a pipe.

    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.

    An empty directory returns 0 for me

    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.

    Wow I can't believe that something so easily done in Windows with "dir" can be so cumbersome with Linux :|

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM