views:

96

answers:

3

I want to write a bash script which will use a list of all the directories containing specific files. I can use find to echo the path of each and every matching file. I only want to list the path to the directory containing at least one matching file.

For example, given the following directory structure:

dir1/
    matches1
    matches2
dir2/
    no-match

The command (looking for 'matches*') will only output the path to dir1.

As extra background, I'm using this to find each directory which contains a Java .class file.

+6  A: 
find -name '*.class' -printf '%h\n' | sort -u

From man find:

-printf format

%h Leading directories of file’s name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to ".".

John Kugelman
+1 That'd do it.
Hans W
+1 Worked a treat.
Grundlefleck
You should use sort -u instead of uniq, as the output may not be in order. Consider this order of traversal: dir1/matches1 dir1/dir3/matches3 dir1/matches2 - this will output dir1 dir1/dir3 dir1 and uniq will not deduplicate this as it is not sorted.Edit: As Jim has as another answer.
camh
+2  A: 

GNU find

find /root_path -type f -iname "*.class" -printf "%h\n" | sort -u
ghostdog74
+1 did exactly as I'd asked.
Grundlefleck
+1  A: 
find / -name *.class -printf '%h\n' | sort --unique
Jim