All for Joomla All for Webmasters

Count the total number of files contained in a directory


Count the total number of files contained in a directory

Surely you Linux user at some point in their lives have used the terminal to list the contents of a directory or even navigate between them. Although there are numerous tools (GUI) for this purpose. And today I will demonstrate how to count the total number of existing files in a given directory using good old Shell. Recalling that the Shell is the land of opportunities where we can create numerous solutions to the same problem.

For this I created the / test located in the home of my user and within that there are 17 text files.

you learnlinux @: ~ / test $ ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 11.txt 12.txt 13.txt 14.txt 15.txt 16.txt 17.txt

The task is quite simple. I will use the ls command to list the files in the directory, but for our it is necessary that a list with one file per line is generated; I will use for this parameter -1.

you learnlinux @: ~ / test $ ls -1
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt
11.txt
12.txt
13.txt
14.txt
15.txt
16.txt
17.txt

Now, with command will perform the count. For those who do not know, the total of characters, words or lines of a file or expression. In this specific case, I will use with the -l parameter indicating the total number of lines.

you learnlinux @: ~ / test $ ls -1 | wc -l
17

It is working and almost ready. To get better I will create a function that will call her take TOTAL_FILES where we can specify the directory from which we want to count the files.

$ TOTAL_FILES ()  { ls “$ * ” | wc -l; }

testing:

you learnlinux @: ~ / test $ TOTAL_FILES.
17
you learnlinux @: ~ / test $ TOTAL_FILES / etc.
241
you learnlinux @: ~ / test $ TOTAL_FILES / home
2
you learnlinux @: ~ / test $ TOTAL_FILES /etc/init.d/
68

Okay, we have a function that “works”, simple and fast. As I said earlier, the Shell is the land of possibilities and these possibilities will create a function that does exactly the same thing, but using only expansion variables and globbing.

TOTAL_FILES $ () {  f = ( “$ *” / * ) ; echo  $ {# f [@] } ; }

Testing …

you learnlinux @: ~ / test $ TOTAL_FILES.
37
you learnlinux @: ~ / test $ TOTAL_FILES / etc.
241
you learnlinux @: ~ / test $ TOTAL_FILES / home
2
you learnlinux @: ~ / test $ TOTAL_FILES /etc/init.d/
68

Well, I hope that this function can be useful when you need it and be sure to train your creativity, develop their own solutions. So thanks, thank you and see you soon.


Like it? Share with your friends!

0
, 0 points

Count the total number of files contained in a directory

log in

Become a part of our community!

reset password

Back to
log in
Choose A Format
Personality quiz
Trivia quiz
Poll
Story
List
Meme
Video
Audio
Image