51

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)

2 Answers 2

89

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 {} +
5
  • 3
    Thank you! 12.000 files gone i 2 sec. That saved me some manual labour! Jul 30, 2013 at 13:45
  • Neither -delete nor -exec rm worked for me in Bash on Windows. But this did: find /path/to/directory -type f -name '*[0-9]x[0-9]*[0-9]x[0-9]*.jpg' | xargs rm
    – Tamlyn
    Aug 13, 2015 at 8:30
  • 2
    @Tamlyn Use -print0 and xargs -0, otherwise the command will fail with file names containing spaces or single quotes. But -delete and -exec rm do work on Windows. If something doesn't work, it's not due to their use. Aug 13, 2015 at 9:50
  • Will this work with Windows as well? Aug 25, 2015 at 4:07
  • It'll work if you have a port of Unix utilities such as Cygwin or GNUWin32. Obviously it won't work out of the box on Windows. Take care that Windows has an unrelated program called find, so make sure the Unix utilities are first in PATH. Aug 25, 2015 at 8:33
0

The right command is:

find . -type f -iregex '.*[0-9]x[0-9]*\.jpg$'

this will grab only files with names: 'aaa-12x12.jpg', but not 'aaa-12x12red.jpg'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.