Reputation: 3592
I've spent quite some time trying to figure out why this regex doesn't match files with names like:
/var/tmp/app.0.attachments
....
/var/tmp/app.11.attachments
sudo rm -rf /var/tmp/app/\.([0-9]{1}|1[0-1]{1})/\.attachments
$: -bash: syntax error near unexpected token `('
I've tried escaping [
, ]
, |
and {}
Please help.
Upvotes: 0
Views: 217
Reputation: 361595
Regexes do not work at the shell. Shells do globbing, which is simpler and not as powerful. With the default globbing, the best you can do is something like:
sudo rm -rf /var/tmp/app/app.[0-9]*.attachments
If you enable extended globbing, you can add pipes and grouping to the toolset.
shopt -s extglob
sudo rm -rf /var/tmp/app/app.@([0-9]|1[0-1]).attachments
Note the different syntax. It's not regex, but it's similar. From the bash(1) man page:
If the extglob shell option is enabled using the
shopt
builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a|
. Composite patterns may be formed using one or more of the following sub-patterns:?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns
Another alternative would be to use find
, which can do both globbing and regexes.
sudo find /var/tmp -regex '/var/tmp/app\.\([0-9]\|1[0-1]\)\.attachments' -delete
sudo find /var/tmp -regex '/var/tmp/app\.\([0-9]\|1[0-1]\)\.attachments' -exec rm -rf {} +
Note that it performs a match on the entire path, not just the file name. You also have to escape \(
, \)
, and \|
.
Upvotes: 0