Thursday, May 2, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 1852  / 2 Years ago, thu, june 23, 2022, 8:19:35

Source: Any directory tree with any number and type of files. Q: How many .jpg or .jpg and .png (for example) are in each subdirectory?


How can I limit the code below for files with 1 or more specific extension(s)? Having trouble inserting the -type f -name "*.jpg*", for example.


for DIR in $(find . -maxdepth 99 -type d)
do
printf "%10d %s
" $(find ${DIR}|wc -l) "${DIR}"
done

Desired output:


118   ./aaa
73 ./aaa/bbb
16 ./aaa/bbb/ccc

If more than one file types are counted, then their combined total number in each subdirectories should be displayed.


More From » command-line

 Answers
6

Probably this find|xargs solution will work as you need.


find . -mindepth 1 -maxdepth 99 -type d -print0 | 
xargs -0 -i bash -c 'printf "%10d %s
" "$(find "$1" -maxdepth 1 -type f -regextype awk -iregex ".*.(jpg|jpeg|png)" | wc -l)" "$1"' - '{}'

Some explanations:



  • The -mindepth 1 option is added in order to skip the current directory and process only the sub directories.

  • The -print0 provides the output entries with null delimiter, it works together with the -0 option of xargs.

  • The option - "{}" at the end will pass the xargs argument as value of the first positional parameter $1 of the bash command.

  • Within the second find command -iregex means case insensitive regular expression (you could use -regex instead).


[#797] Saturday, June 25, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kroapathe

Total Points: 445
Total Questions: 117
Total Answers: 99

Location: Botswana
Member since Sun, Sep 19, 2021
3 Years ago
;