18

Lets say I have 20 files named FOOXX, where XX is the number of the file, eg 01, 02 etc.

At the moment, if I want to delete all files lower than the number 10, this is easy and I just use a wildcard, eg rm FOO0*

However, if I want to delete specific files ina range, eg 13-15, this becomes more difficult.

rm FPP[13-15] does not work, and asks me if I wish to delete all files. Likewse rm FOO1[3-5] wishes to delete all files that begin with FOO1

So, what is the best way to delete ranges of files like this?

I have tried with both bash and zsh, and I don't think they differ so much for such a basic task?

  • "... rm FOO1[3-5] wishes to delete all files that begin with FOO1" This makes no sense, and certainly isn't the case here. – Ignacio Vazquez-Abrams May 6 '10 at 12:23
  • @Ignacio yeah- I'd like to see the character set has that collation order! – kmarsh May 6 '10 at 12:52
31

In bash you can use:

rm FOO1{3..5}

or

rm FOO1{3,4,5}

to delete FOO13, FOO14 and FOO15.

Bash expansions brace are documented here.

13

For future readers, the find command can also delete files. I settled on this for a similar problem:

find . -type f -regex '...' -delete

but the chosen answer is the simplest anser to this question.

  • The chosen answer is only good for files that follow a naming convention though. Thanks to your answer, I could just delete all object files in a directory. (in my case I just went with find . -name "*.o" -delete and it worked like a charm) – John Hamilton Feb 24 '18 at 11:20
6

ls | grep regex | xargs rm

  • 6
    You should use find -regex ... -print0 | xargs -0 ... for this, otherwise it fails for filenames with spaces. – Paused until further notice. May 6 '10 at 13:02
  • 1
    Of course, if you're going to use find then you may as well just use -exec. – Ignacio Vazquez-Abrams May 6 '10 at 13:31
  • In my case the files had spaces, and changing the delimiter fixes the spaces issue: ls | grep regex | xargs --delimiter='\n' rm – Anake Apr 1 '12 at 20:38
  • 1
    -1 for attempting to parse ls – evilsoup May 24 '13 at 21:18
  • @evilsoup, +1 for adding that warning, but, who inserts a new line in a file name? – Iulian Onofrei Feb 22 '17 at 15:20

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.