Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Assume starting at some directory in the filesystem. This base directory has lots of subdirectories (not nested!). Each of the subdirectories has an arbitrary number of files withing.

How can I find all directories having e.g. less than 3 files inside using some shell command? The find command has some nice options for dealing with size of files, but I could not find anything regarding file count.

share|improve this question

2 Answers 2

up vote 4 down vote accepted
$ find . -type d | while read d; do if [ $(ls -1 "$d" | wc -l) -lt 3 ]; then echo $d; fi; done
share|improve this answer

How about this:

for i in `find /etc/ -type d `; do j=`ls -1 $i | wc -l` ; if [ $j -le  3 ]; then echo "$i has about $j file(s)"; fi; done

Output:

[root@kerberos ~]# for i in `find /etc/ -type d `; do j=`ls $i | wc -l` ; if [ $j -le  3 ]; then echo "$i has about $j file(s)"; fi; done
/etc/prelink.conf.d has about 0 file(s)
/etc/kdump-adv-conf has about 2 file(s)
/etc/kdump-adv-conf/kdump_initscripts has about 2 file(s)
/etc/kdump-adv-conf/kdump_sample_manifests has about 1 file(s)
/etc/openldap/slapd.d.backup has about 2 file(s)
/etc/openldap/ssl has about 2 file(s)
/etc/foomatic has about 2 file(s)
/etc/gtk-2.0 has about 2 file(s)
/etc/gtk-2.0/x86_64-redhat-linux-gnu has about 2 file(s)

. . . etc

I tried to do it within the -exec, but I got impatient and just piped the output and parse it out instead.

EDIT: Took note of Quantas use of -1 and incorporated it into my script, since you can't assume that the output will be in a single column. I did, however, leave the less than or equal operator in the script.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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