0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, thanks! If I wanted to loop through a series of subdirectories and use this snippet how would I go about doing this? I guess I could just cd into each subdirectory and call it, but is there a way to apply this to all files in all subdirectories?
Also, I do not always want to check for extensions, that was just an example, is there a way to check if any of the array elements are anywhere in the filename? E.g.: json.docx would be removed in this case but I would want to keep it since it contains json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.