I have a scenario where I am looping through all directories and subdirectories in a given path; if a file with specific extension (.txt) is found, store the name of the directories and subdirectories in an array. Later, I read and execute commands on those directories.
Here is what I am performing:
!/bin/bash
x=( $(find . -name "*.txt") ); echo "${x[@]}"
for item in "${x[@]}"; { echo "$item"; }
My current output is:
./dir1/file1.txt
./dir1/file2.txt
./dir2/subdir1/subdir2/file3.txt
but what I want to achieve is in the array x
there should not be any duplicates even if the dir contains more than one .txt
file. Additionally, I don't want to store the file name in as a path; the array should contain only the directory name.
The expected output:
./dir1
./dir2/subdir1/subdir2/
-printf '%h\n'
(or better,-printf '%h\0'
withsort -zu
) to get the leading path components, which avoids the shell loop - see Why is looping over find's output bad practice? – steeldriver Mar 03 '22 at 17:17mkdir -p 'foo /*/*/*/* *.txt'
for instance. – Stéphane Chazelas Mar 03 '22 at 18:18