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.
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.
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.
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"."
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With