Today’s article probably isn’t all that useful unless, of course, you want to count the number of files in a directory. This can be useful if you want to quickly see if all the files were copied over or the like. Maybe you’ve made a backup and want to ensure the number of files matches. Who knows? It’s your terminal, you do what you want!
This article comes from my notes. These notes were right next to the notes used for the last article, where we learned to count letters, words, and lines in a file. I did get some feedback about why some folks want to know that information, which is always good feedback as far as I’m concerned. It’s great to learn the ways you put these commands to work.
Seeing as I’m lazy and just using the next notes in line, we’ll be using the ‘wc’ command again. If you didn’t read yesterday’s article, or got here by way of a search engine result, then the wc command describes itself like this:
wc – print newline, word, and byte counts for each file
You can expect the wc command to be included in every distro. It is a fundamental application and small enough to be a default application. Even the tiniest desktop distros will likely have this application and you won’t need to install anything. You will need an open terminal.
Count The Number Of Files In A Directory:
As I said in the intro, you’re going to need to use the terminal. Regular readers will notice a trend. We use the terminal a great deal. Just press
With your terminal now open, navigate to your favorite directory with:
Then, when you’re there, try the following command:
ls | wc -l
You can also specify the path, just like you would with the regular ls command. That’d be something like:
ls /path/to/directory | wc -l
If you want to count all the files, including the hidden files, the command would be quite similar:
ls -a /path/to/directory +| wc -l
In case any of this is unclear, I’ve made an image showing how I can count the number of files in a directory with a few similar commands. It looks like this:
As always, be sure to check the man page for both of these commands:
So, have fun counting the number of files in a directory – while learning a bit about ls, wc, and the almighty pipe (which I’ve not yet written about in any great detail).
Of course, I hope you have fun with this one. I’m not sure how many creative ways you can use this set of commands, but it’s nice to use the pipe in an article, even if it’s just one where we count the number of files in a directory. We did use it in a fun article about cowsay and fortune. It has also been used in a few other articles, but we should have an article all about it.
Thanks for reading! If you want to help, or if the site has helped you, you can donate, register to help, write an article, or buy inexpensive hosting to start your site. If you scroll down, you can sign up for the newsletter, vote for the article, and comment.