How to count files at commandline in Ubuntu

Is there a way to easily count how many files and directories match a given pattern? Thankfully, this is easy to do at the commandline with the ls and wc programs. ls can be used to list files that match the pattern you want and wc can be used to count them.

Assume we want to count how many files or directories have prefix Foo.

First, let us see what does not work:

$ ls -l Foo* | wc -l

This is ls with its -l (EL, not ONE) parameter. It lists the files that match and you pipe it to wc to count the number of lines it receives.

This almost works, except that ls -l puts an extra line at the beginning that shows the number of blocks used by that directory.

Instead, use ls -1 (that is ONE, not EL) parameter which gives exactly what you want:

$ ls -1 Foo* | wc -l

Tried with: Ubuntu 12.04.1 LTS

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.