Reputation: 311
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
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