I Tried to delete files that starts with A and ends with 2 numbers but It doesn't do a thing.
What I tried:
rm ^A*[0..9]2$
Where am I wrong?
You can use the following command to delete all files matching your criteria:
ls | grep -P "^A.*[0-9]{2}$" | xargs -d"\n" rm
How it works:
ls
lists all files (one by line since the result is piped).
grep -P "^A.*[0-9]{2}$"
filters the list of files and leaves only those that match the regular expression ^A.*[0-9]{2}$
.*
indicates any number of occurrences of .
, where .
is a wildcard matching any character.
[0-9]{2}
indicates exactly two occurrences of [0-9]
, that is, any digit.
xargs -d"\n" rm
executes rm line
once for every line
that is piped to it.
Where am I wrong?
For starters, rm
doesn't accept a regular expression as an argument. Besides the wildcard *
, every other character is treated literally.
Also, your regular expression is slightly off. For example, *
means any occurrences of ...
in a regular expression, so A*
matches A
, AA
, etc. and even an empty string.
For more information, visit Regular-Expressions.info.
grep -P
(Perl regex). grep -E
may work in this case.
Commented
Oct 2, 2013 at 20:59
-I
with xargs
and always test with non-lethal commands first: xargs -d"\n" -I {} echo "{}"
ls
? See this question which points to this article. Because of the pitfalls you may rm
what you don't want to.
Commented
Nov 15, 2016 at 11:57
Or using find
:
find your-directory/ -name 'A*[0-9][0-9]' -delete
This solution will deal with weird file names.
-type f
Commented
Jun 8, 2016 at 8:12
xargs
approach with rm -f
.
See the filename expansion section of the bash man page:
rm A*[0-9][0-9]
find
command works with regexes as well.
Check which files are gonna to be deleted
find . -regex '^A.*[0-9]{2}$'
Delete files
find . -regex '^A.*[0-9]{2}$' -delete
-regextype egrep
to make {x,y}
type quantifiers work.
Commented
Jul 10, 2020 at 15:05
The solution with regexp is 200 times better, even with that you can see which file will be deleted before using the command, cutting off the final pipe:
ls | grep -P "^A.*[0-9]{2}$"
Then if it's correct just use:
ls | grep -P "^A.*[0-9]{2}$" | xargs -d "\n" rm
This is 200 times better because if you work with Unix it's important to know how to use grep. It's very powerful if you know how to use it.