How to delete files on the command line with regular expressions?
Solution 1
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.
Solution 2
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.
Solution 3
ls | grep regex | xargs rm
Related videos on Youtube
Jack
Updated on September 17, 2022Comments
-
Jack over 1 year
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?
-
kmarsh about 14 years@Ignacio yeah- I'd like to see the character set has that collation order!
-
-
Ignacio Vazquez-Abrams about 14 yearsOr even
rm FOO{13..15}
. -
Jack about 14 yearsIs this also true for ZSH?
-
Dennis Williamson about 14 yearsYou should use
find -regex ... -print0 | xargs -0 ...
for this, otherwise it fails for filenames with spaces. -
Dennis Williamson about 14 years@Jack: Yes, it is.
-
Ignacio Vazquez-Abrams about 14 yearsOf course, if you're going to use
find
then you may as well just use-exec
. -
Anake about 12 yearsIn my case the files had spaces, and changing the delimiter fixes the spaces issue: ls | grep regex | xargs --delimiter='\n' rm
-
evilsoup almost 11 years-1 for attempting to parse ls
-
abhinavkulkarni over 10 years@Jack:
bash
commands form subset ofz
shell commands. -
Aditya M P over 10 yearsSo I need to learn both regex and globbing syntax. Boohoo. :)
-
Iulian Onofrei about 7 years@evilsoup, +1 for adding that warning, but, who inserts a new line in a file name?
-
Iulian Onofrei about 7 years@DennisWilliamson, Shouldn't it be
find . -regex ... -print0 | xargs -0 ...
instead? -
Iulian Onofrei about 7 years@IgnacioVazquez-Abrams, How?
-
Dennis Williamson about 7 years@IulianOnofreiIn GNU
find
the current directory is implied. You can omit the.
-
Iulian Onofrei about 7 years@DennisWilliamson So the problem is only on mac, where it throws the error
find: illegal option -- r
. -
John Hamilton about 6 yearsThe 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)