52

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

90

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! Commented 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
    Commented 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. Commented Aug 13, 2015 at 9:50
  • Will this work with Windows as well? Commented 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. Commented 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'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .