I want to find the total count of the number of files under a folder and all its sub folders.
10 Answers
Maybe something like this will do the trick:
find . -type f | wc -l
Try the command from the parent folder.
find . -name <pattern> -type ffinds allfiles in the current folder (.) and its subfolders.-name <pattern>only looks for certain files that match the specified pattern. The match is case-sensitive. If you need the match to be case-insensitive, use-inameinstead.- The result (a list of files found) is passed (
|) towc -lwhich counts the number oflines.
- 16,703
- 24,306
Use the tree command. You might need to install the tree package.
It will list all the files and folders under the given folder and list a summary at the end.
- 14,522
The fastest and easiest way, is to use tree. Its speed is limited by your output terminal, so if you pipe the result to tail -1, you'll get immediate result. You can also control to what directory level you like the results, using the -L option. For colorized output, use -C. For example:
$ tree share/some/directory/ | tail -1
558 directories, 853 files
$ tree -L 2 share/some/directory/ | tail -1
120 directories, 3 files
If it's not already there, you can get it here.
find -type f -printf . | wc -c
Don't count the output lines of find, because filenames, containing 99 newlines, will count as 100 files.
- 6,892
Use this command for each folder in the path
for D in *; do echo $D; find $D -type f| wc -l; done
- 474
You can use find . | wc -l
find . will list all files and folders and theire contents starting in your current folder.
wc -l counts the results of find
- 2,470
find seems to be quicker than tree so I used below to count files in each directory of the current working directory (ignoring files in CWD) with allowing directories to have spaces:
ls -d */ | while read dir_line
do
echo -n "$dir_line :"
find "$dir_line" -type f | wc -l
done
- 161
Benchmark on find vs ls vs tree
hyperfine \
> "find . -type f | wc -l" \
> "ls -lR | grep ^- | wc -l" \
> "tree . | tail -1"
Benchmark 1: find . -type f | wc -l
Time (mean ± σ): 3.070 s ± 0.030 s [User: 0.284 s, System: 2.827 s]
Range (min … max): 3.038 s … 3.126 s 10 runs
Benchmark 2: ls -lR | grep ^- | wc -l
Time (mean ± σ): 5.887 s ± 0.054 s [User: 0.896 s, System: 5.160 s]
Range (min … max): 5.845 s … 6.020 s 10 runs
Benchmark 3: tree . | tail -1
Time (mean ± σ): 4.475 s ± 0.089 s [User: 1.254 s, System: 3.280 s]
Range (min … max): 4.349 s … 4.677 s 10 runs
Summary
'find . -type f | wc -l' ran
1.46 ± 0.03 times faster than 'tree . | tail -1'
1.92 ± 0.03 times faster than 'ls -lR | grep ^- | wc -l'
find seem more efficient on my dir
- 101