Bash Scripting – How to Delete Files Matching a Pattern

bashfilesfindwildcards

I need to recursively remove all files in all subdirs where the filename contains a number followed by an 'x' followed by a number, at least two times.

Example:

I'd want to remove these files:

'aaa-12x123-123x12.jpg'
'aaa-12x12-123x12-12x123.jpg'

But I do NOT want to remove these files:

'aaa.jpg'
'aaa-12x12.jpg'
'aaaxaaa-123x123.jpg'
'aaaxaaa-aaaxaaa.jpg'

How can I do that (from the bash shell)

Best Answer

A string contains “a number followed by an x followed by a number” if and only if it contains a digit followed by an x followed by a digit, i.e. if it contains a substring matching the pattern [0-9]x[0-9]. So you're looking to remove the files whose name matches the pattern *[0-9]x[0-9]*[0-9]x[0-9]*.jpg.

find /path/to/directory -type f -name '*[0-9]x[0-9]*[0-9]x[0-9]*.jpg' -delete

If your find doesn't have -delete, call rm to delete the files.

find /path/to/directory -type f -name '*[0-9]x[0-9]*[0-9]x[0-9]*.jpg' -exec rm {} +
Related Question