how to

Count number of files in directory and subdirectory in Linux Ubuntu


How to count the number of files in a directory and subdirectory in Linux Ubuntu. Here is a command to find the number of files in a directory in Linux or recursively count the number of files in a directory.

Using ls and wc Commnad

The simplest command to count the number of files in a directory and subdirectories is the ls and wc commands. To use it, just run:

ls | wc -l

Wc counts the number of bytes, characters, space-separated words, and newlines in each given FILE or standard input if none is specified or
for FILE. ‘wc’ prints one line of counters for each file, and if file was given as an argument, it prints the file name after the counters. If more than one FILE is given, ‘wc’ prints the last line containing the total values, with the file name ‘total’. Counters are printed in the following order: newlines, words, characters, bytes, maximum line length.

While “ls” displays information about files (of any type, including directories).

Please note that when we run the ls and wc commands with the -l options, the command will count all files and directories, but not hidden ones. To list hidden files, use the -A option with the ls command:

ls -A | wc -l

If you want to count the number of files, including hidden files, in the current directory, run the following set of commands:

ls -Ap | grep -v /$ | wc -l

In the above command, -p with ls adds / at the end of directory names. The -A option with ls will list all files and directories, including hidden files, but excluding . and .. catalogues. Whereas wc -l counts the number of lines.

Recursively counting files in a directory

Ubuntu Linux users can use the find command to recursively count files in a directory:

find DIR_NAME -type f | wc -l

Linux users can also use the tree command to display the number of files in the current directory and subdirectories:

tree -a

If you want to get the number of files only in the current directory, but not in subdirectories, set the level to 1:

tree -a -L 1

Linux Ubuntu users can run the find command to count the number of files in a directory: the find command will first get all the files and then count them using the wc command. Run the following command:

find directory_path -type f | wc -l

If you don’t want to count the number of files in subdirectories, limit the find command to level 1. Note that level 1 is used for the current directory.

You can run the following command:

find . -maxdepth 1 -type f | wc -l

For those who don’t know, the “find” command searches a directory tree whose root is each filename. This list of files to search is followed by a list of expressions describing the files we want to find.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

Back to top button