Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files of specific file types using shell script

I have a requirement to recursively loop through all the files of certain file types in a directory. The file types is an array variable containing the list of file types that we need to go through for processing. The array values are actually dynamically populated. For the sake of simplicity I am declaring a static array.

 declare -a arr=("pdf" "doc" "txt")

I have the following code to recursively list all the files in the directory, but I am not able to figure out how include the array "arr" to only get back those file types that are included in the array.

find $i -type f -print0 | while read -d $'\0' file; do
    echo $file;
    #Process file
done

Please help me modify the code so that I could retrieve the specified file types only and not all files.

like image 919
tom Avatar asked Dec 12 '25 05:12

tom


1 Answers

I assume that by file types "pdf", "doc", "txt", you mean filenames with those extensions.

If the number of file types is reasonably small (less than a few dozen), then you could build an array of arguments to pass to find in the format:

... -name '*.pdf' -o -name '*.doc' -o -name '*.txt' ...

Assuming that the array of file types is not empty, here's one way to do it (thanks @mike-holt):

arr=(pdf doc txt)

findargs=()

for t in "${arr[@]}"; do
    findargs+=(-name "*.$t" -o)
done

find . -type f \( "${findargs[@]}" -false \)
like image 62
janos Avatar answered Dec 14 '25 19:12

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!