Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo directories containing matching file with Bash?

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.

like image 893
Grundlefleck Avatar asked Feb 17 '10 17:02

Grundlefleck


People also ask

How do I get a list of files in a directory in Bash?

Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.

How do I list only directories in ls?

Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.


1 Answers

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

like image 137
John Kugelman Avatar answered Oct 31 '22 12:10

John Kugelman