This is the folder structure that I have.
Using the find command find . -type d
in root
folder gives me the following result
Result
./folder1
./folder1/folder2
./folder1/folder2/folder3
However, I want the result to be only ./folder1/folder2/folder3
. i.e only print the result if there's a file of type .txt
present inside.
Can someone help with this scenario? Hope it makes sense.
CodePudding user response:
You may use this find
command that finds all the *.txt
files and then it gets unique their parent directory names:
find . -type f -name '*.txt' -exec bash -c '
for f; do
f="${f#.}"
printf "%s\0" "$PWD${f%/*}"
done
' _ {} | awk -v RS='\0' '!seen[$0] '
- We are using
printf "%s\0"
to address directory names with newlines, spaces and glob characters. - Using gnu-awk to get only unique directory names printed
CodePudding user response:
Using Associative array and Process Substitution.
#!/usr/bin/env bash
declare -A uniq_path
while IFS= read -rd '' files; do
path_name=${files%/*}
if ((!uniq_path["$path_name"] )); then
printf '%s\n' "$path_name"
fi
done < <(find . -type f -name '*.txt' -print0)
Check the value of uniq_path
declare -p uniq_path