Counting files in a Linux directory is a common task used daily. Here are two ways to do it using Bash.
  
  
  1. Using the ls and wc Commands
The ls -1 command lists directory contents one per line. Piping the output to  wc -l counts the lines, giving the total number of files. Example:
ls -1 ~/Documents | wc -l
# 25
To include hidden files (starting with .), add the -a option to ls. Example:
ls -a1 ~/Documents | wc -l
# 30
  
  
  2. Using the find and wc Commands
The find command lists all files and directories in a path recursively. Piping the output to wc -l  counts the lines, giving the total number of files. Example:
find ~/Documents | wc -l
## 105
To count files by searching for a specific name or file extension, add the -iname option.
find ~/Documents -iname "*.mp4" | wc -l
## 14
find ~/Documents -iname "*jobs*" | wc -l
## 44
To count only files, add the -type option with the value f. Example:
find ~/Documents -type f | wc -l
## 87
To count only directories, add the -type option with the value d. Example:
find ~/Documents -type d | wc -l
## 29
    
Top comments (0)