'Bash How to find directories of given files
I have a folder with several subfolders and in some of those subfolders I have text files example_1.txt, example_2.txt and so on. example_1.txt may be found in subfolder1, some subfolders do not contain text files.
How can I list all directories that contain a text file starting with example?
I can find all those files by running this command
find . -name "example*"
But what I need to do is to find the directories these files are located in? I would need a list like this subfolder1, subfolder4, subfolder8 and so on. Not sure how to do that.
Solution 1:[1]
You must be use the following command,
find . -name "example*" | uniq -u | awk -F / '{print $2}'
Solution 2:[2]
- find all files in subfolders with mindepth 2 to avoid this folder (.)
- get dirname with xargs dirname
- sort output-list and make folders unique with sort -u
- print only basenames with awk (delimiter is / and last string is $NF). add "," after every subfolder
- translate newlines in blanks with tr
- remove last ", " with sed
list=$(find ./ -mindepth 2 -type f -name "example*"|xargs dirname|sort -u|awk -F/ '{print $NF","}'|tr '\n' ' '|sed 's/, $//')
echo $list
flow, over, stack
Solution 3:[3]
Suggesting find command that prints only the directories path.
Than sort the paths.
Than remove duplicates.
find . -type f -name "example*" -printf "%h\n"|sort|uniq
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robert |
| Solution 2 | |
| Solution 3 | Dudi Boy |
