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.
From
man find
:GNU find
Far too late, but this might be helpful to future readers: I personally find it more helpful to have the list of folders printed into a file, rather than to Terminal (on a Mac). For that, you can simply output the paths to a file, e.g. folders.txt, by using:
find . -name *.sql -print0 | xargs -0 -n1 dirname | sort --unique > folders.txt
On OS X and FreeBSD, with a
find
that lacks the-printf
option, this will work:The
-n1
inxargs
sets to 1 the maximum number of arguments taken from standard input for each invocation ofdirname
Ok, i come way too late, but you also could do it without find, to answer specifically to "matching file with Bash" (or at least a POSIX shell).
The
${VARNAME%/*}
will strip everything after the last/
(if you wanted to strip everything after the first, it would have been${VARNAME%%/*}
).Regards.