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.
CodePudding user response:
You must be use the following command,
find . -name "example*" | uniq -u | awk -F / '{print $2}'
CodePudding user response:
- 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
CodePudding user response:
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