0

I have hundreds of directories in videos directory. I want to count number of files of each sub-directory. For each sub-directory, I can use ls -1 | wc -l to count number of files in it. But I can not manually repeat the command hundred times. Could you please tell me other commands to count number of files of each sub-directory? Thank you so much.

3

Simple use of find and wc

MusicDir='/home/MyUser/Music'
find "$MusicDir" -type d | while read D; do echo -e "$(find "$D" -type f | wc -l)\t$D"; done

## Example OUTPUT
206 ./AC-DC
9   ./AC-DC/1975 - High Voltage (Australia Only)
11  ./AC-DC/1975 - T.N.T (Australia Only)
10  ./AC-DC/1976 - Dirty Deeds Done Dirt Cheap (International version)
10  ./AC-DC/1976 - High Voltage (International version)
10  ./AC-DC/1977 - Let There Be Rock
11  ./AC-DC/1978 - Powerage
11  ./AC-DC/1979 - Highway To Hell
13  ./AC-DC/1980 - Back In Black
11  ./AC-DC/1981 - For Those About To Rock (We Salute You)
11  ./AC-DC/1983 - Flick Of The Switch
6   ./AC-DC/1984 - 74 Jailbreak
11  ./AC-DC/1985 - Fly On The Wall
11  ./AC-DC/1988 - Blow Up Your Video
14  ./AC-DC/1990 - The Razor's Edge
13  ./AC-DC/1995 - Ballbreaker
13  ./AC-DC/2000 - Stiff Upper Lip
16  ./AC-DC/2008 - Black Ice
12  ./AC-DC/2014 - Rock or Bust

The output could also be sorted (second column, alpha)

MusicDir='/home/MyUser/Music'
find "$MusicDir" -type d | while read D; do echo -e "$(find "$D" -type f | wc -l)\t$D"; done | sort -k2
1
  • 1
    I’d consider adding -maxdepth 1 to disable recursion into subdirectories and -mindepth 1 to disable counting . but in a well-defined special case, the original command might work well.
    – Melebius
    Aug 13 '20 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.