views:

2434

answers:

4

I want to get a list of folders at the current level (not including their subfolders) and simply print the folder name and a count of the number of files in the folder (preferably filtering to *.jpg if possible).

Is this possible in the standard bash shell? ls -l prints about everything but the file count :)

+3  A: 

I've come up with this one:

find -maxdepth 1 -type d | while read dir; do 
    count=$(find "$dir" -maxdepth 1 -iname \*.jpg | wc -l)
    echo "$dir ; $count"
done

Drop the second -maxdepth 1 if the search within the directories for jpg files should be recursive considering sub-directories. Note that that only considers the name of the files. You could rename a file, hiding that it is a jpg picture. You can use the file command to do a guess on the content, instead (now, also searches recursively):

find -mindepth 1 -maxdepth 1 -type d | while read dir; do 
    count=$(find "$dir" -type f | xargs file -b --mime-type | 
            grep 'image/jpeg' | wc -l)
    echo "$dir ; $count"
done

However, that is much slower, since it has to read part of the files and eventually interpret what they contain (if it is lucky, it finds a magic id at the start of the file). The -mindepth 1 prevents it from printing . (the current directory) as another directory that it searches.

Johannes Schaub - litb
A: 
#!/bin/bash
for dir in `find . -type d | grep -v "\.$"`; do
echo $dir
ls $dir/*.jpg | wc -l
done;
John Ellinwood
A: 

mine is faster to type from the command line. :)

do the other suggestions offer any real advantage over the following?

find -name '*.jpg' | wc -l               # recursive


find -maxdepth 1 -name '*.jpg' | wc -l   # current directory only
42
example: teacher wants to lists jpg pics of his pupils. so he puts the command in /home and wants to list all jpg in those sub-dirs to validate they don't contain some *** things :) example of my previous unix-teacher. he knew of what he was speaking :p ppls tried to hide their pr0n in bin files :D
Johannes Schaub - litb
That only prints the total number of files, not the number per folder. I've done it now anyway, following the comment above.
DisgruntledGoat
@DisgruntledGoat, I misread your question. Sorry about that. I understand now.
42
A: 

You can do it without external commands:

for d in */; do 
  set -- "$d"*.jpg
  printf "%s: %d\n" "${d%/}" "$#"
done

Or you can use awk (nawk or /usr/xpg4/bin/awk on Solaris):

printf "%s\n" */*jpg |
  awk -F\/ 'END { 
    for (d in _) 
      print d ":",_[d] 
      }
  { _[$1]++ }'
radoulov