Command Line Basics: Count Files

January 21, 2010 by
Filed under: command line, HowTo, linux 

You may have an occasion that you want to know the number of files in a directory. There are a couple of simple ways to do this. The first way is to list the files with ls and count them with wc. No, wc doesn't stand for the place you go to relieve yourself; in this case, it stands for word count. The command looks like this:

ls -A | wc -l

This command works pretty well, but has one drawback. It will count everything that ls outputs, including directories. You will get the same results from:

ls -A | grep -c .

In this command, grep -c counts all the files that match the "." wildcard.

What if you don't want directories listed? With some additional options you can add some indicators to the directory and symbolic link listings and then filter them out with grep. The -F switch on ls will add the indicators. The -v switch on grep will be used to exclude the indicator patterns.

Affiliate Link

To count all files except directories, use this command.

ls -AF | grep -vc /

To include directories, but not symbolic links, use:

ls -AF | grep -vc @

To count files excluding directories and symbolic links, use:

ls -AF | grep -vc [/,@]

Comments

4 Responses to “Command Line Basics: Count Files”

  1. Wade says:

    Mike's reply works recursively. To make Linerd's post work recursivley, just add the -R switch: ls -AFR | grep -vc [/,@]

  2. Mike says:

    This works too

    find . -type f | wc -l

  3. Story added...

    This story has been submitted to fsdaily.com! If you think this story should be read by the free software community, come vote it up and discuss it here:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>