How to echo directories containing matching file with Bash?

30,362

Solution 1

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 ".".

Solution 2

On OS X and FreeBSD, with a find that lacks the -printf option, this will work:

find . -name *.class -print0 | xargs -0 -n1 dirname | sort --unique

The -n1 in xargs sets to 1 the maximum number of arguments taken from standard input for each invocation of dirname

Solution 3

GNU find

find /root_path -type f -iname "*.class" -printf "%h\n" | sort -u

Solution 4

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).

ls */*.class | while read; do
  echo ${REPLY%/*}
done | sort -u

The ${VARNAME%/*} will strip everything after the last / (if you wanted to strip everything after the first, it would have been ${VARNAME%%/*}).

Regards.

Solution 5

find / -name *.class -printf '%h\n' | sort --unique
Share:
30,362
Grundlefleck
Author by

Grundlefleck

Technical lead; open-source author and contributor; conference speaker. I care deeply about building software to solve problems. Whether I’m creating delightful user experiences; building tools for fellow developers; improving performance and reliability of mission critical systems; or removing friction in the everyday tasks of colleagues, I find joy in making people’s lives easier.

Updated on September 25, 2021

Comments

  • Grundlefleck
    Grundlefleck over 2 years

    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.