PedsB
PedsB

Reputation: 311

How to check if filename contains any element in array in bash

Say I have an array: myarray=( json txt png )

And say I have a directory containing files with all sorts of extensions: somefile.png, file2.docx, etc.

How would I go about looping through all files, and if they don't have any of the extensions in the array, remove them? I know I could loop over each file, then loop over all array elements and check them individually, but I was wondering if there was a way to compare a string to an entire array (which seems to be contrary to the majority of questions that I've found: Where you have an array and you check to see if a given string is found in the array)

Upvotes: 0

Views: 278

Answers (1)

anubhava
anubhava

Reputation: 785058

Using bash extglob, you may do this:

shopt -s extglob nullglob
myarray=( json txt png )
patt=$( IFS='|'; echo "${myarray[*]}" )
echo rm !(*@($patt)*) **/!(*@($patt)*)

Once you're satisfied with the output, remove echo before rm.

Upvotes: 1

Related Questions