Re: How to find dirs with single item
On Thu, 29 May 2014 14:31:03 -0500
Dennis Wicks <wix@mgssub.com> wrote:
> Can't quite figure out how to do this.
>
> I'd like to be able to scan a Volume or directory and find
> all directories that have only one item in them. Either
> directory or file.
>
> Any ideas??
This one
* wraps around find utility so that you can easily add
further constraints (those will only apply to the directory
you search, not to the child),
* works in good-old `sh`,
* returns true if found at least 1 (similar to grep),
* does not "slurp" the whole list, i.e. should start
printing matches ASAP instead of waiting for find to finish:
#!/bin/sh
filter_single_item() {
rv=1
while read path;
do
test $(ls "$path" | wc -l) -eq 1 && echo "$path" && rv=0
done
return $rv
}
find "$@" -type d | filter_single_item
Yes it's quite ineffective as it creates at least 3 processes
per each dir it scans, but it depends on your case if it's
problem.
OTOH, if you are sure no dir contains space, you could use
`echo` instead of ls and add -w option to wc. Eventually you
could even replace wc with some trick with variable expansion.
(probably switching to bash for better tricks).
aL.
--
Alois Mahdal
Reply to: