20

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 FOO[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?

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

3 Answers 3

33

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.

5
  • 3
    Or even rm FOO{13..15}. May 6, 2010 at 12:24
  • Is this also true for ZSH?
    – Jack
    May 6, 2010 at 12:51
  • @Jack: Yes, it is. May 6, 2010 at 13:07
  • @Jack: bash commands form subset of z shell commands. Aug 14, 2013 at 0:36
  • So I need to learn both regex and globbing syntax. Boohoo. :)
    – Aditya M P
    Oct 25, 2013 at 11:00
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.

1
  • 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) Feb 24, 2018 at 11:20
6

ls | grep regex | xargs rm

9
  • 6
    You should use find -regex ... -print0 | xargs -0 ... for this, otherwise it fails for filenames with spaces. May 6, 2010 at 13:02
  • 1
    Of course, if you're going to use find then you may as well just use -exec. May 6, 2010 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, 2012 at 20:38
  • 1
    -1 for attempting to parse ls
    – evilsoup
    May 24, 2013 at 21:18
  • @evilsoup, +1 for adding that warning, but, who inserts a new line in a file name? Feb 22, 2017 at 15:20

You must log in to answer this question.

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