find all directories having less than x files inside

Solution 1:

$ find . -type d | while read d; do if [ $(ls -1 "$d" | wc -l) -lt 3 ]; then echo $d; fi; done

Solution 2:

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.