Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to count files at commandline in Ubuntu

📅 2013-Jan-29 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ count, ls, ubuntu, wc ⬩ 📚 Archive

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧