How To Count All Files in Directory From The Terminal
November 18, 2019 in Technology | 2 mins read | Tagged: terminal linux macOSSometimes I need to copy directories using the terminal, and I wish to know how many files are there in them. For that, I use some terminal commands to show that piece of info.
If anybody is looking for these, here are the commands and their breakdown.
tl;dr
This command counts all files in a directory and subdirectories:
echo "Directory $(pwd) has $(find . | wc -l) files"
The Breakdown
To avoid doing that recursively, you achieve that by listing all the files and count the lines. That means using either find of ls commands.
Here’s a list of useful parameters using the above two commands:
ls -Flists all the files and the subdirectories in a directory and appends an indicator/to directories names.ls -lathe parameterldisplays a detailed list with info about each file and directory, whilealists hidden files.find . -maxdepth 1finds the files in the directory with the depth set to one; it won’t go into subdirectories.find . -type ffinds only files but not directories in the current directory and subdirectories.find . -type dSame as before but returns the number of subdirectories, not the files in them.
After applying these, we need to clean the returned data (described below) and convert this output into the input of the counting command. For that, we need to use | (pipe) to pipe the data to the next command.
For example who lists all the people or sessions connected to your computer, and then we can count the lines as follows:
who | wc -l where wc with the parameter l counts the lines.
To clean the data coming from the list, we need the following commands:
ls -F | grep -v / | wc -lwhich means, list files, then ignore those with/in their name, then count lines.ls -la | grep ^[-] | wc -llong-lists all files, catch those lines starting with-, then count them.- With
find, no cleaning is needed, go directly to count the lines,find . -maxdepth 1 | wc -lcounts all files and directories on this level. find . -type f | wc -lcounts only files on all levels.find . -type d | wc -lcounts only directories on all levels. And lastly,find . | wc -lcounts everything on this level and in subdirectories.