rm command: remove files with file names containing brackets

2

I am trying to remove all files in a Windows 7 directory with filenames containing brackets; ( and ):

Using MinGW:

rm *(*)*

I get an error:

sh: syntax error near unexpected token '('

I assume this is because the rm command sees a bracket as some sort of special input. What could I do instead?

atomh33ls

Posted 2013-10-08T09:11:49.910

Reputation: 669

Answers

3

You can "escape" specific metacharacters by prefixing with backslash.

$ touch 'aaa(bbb)ccc'
$ rm *\(*\)*
$ ls
$

RedGrittyBrick

Posted 2013-10-08T09:11:49.910

Reputation: 70 632

rm '*(*)*' gives me rm: cannot lstat()*': No such file or directory.rm ()*` works (but also wants to delete directories with this match but that's what the original of the OP wants too, giving an error-line). – Rik – 2013-10-08T09:39:49.557

Using quotes did not work for me. The escape backslash did though. @Rik - Apologies - I was not specific. The directory I am looking at has no sub-directories. – atomh33ls – 2013-10-08T09:45:47.800

1@RedGrittyBrick The first method only works on the one file named *(*)*, but OP wants to work on all files containing ( and ). Try it yourself with a touch 'a(b)c'. Then rm '*(*)*' does not work on all these files. Also not in bash on Linux! The rm *\(*\)* does work on both Linux and mingw. – Rik – 2013-10-08T09:57:14.353

1@Rik: Thanks, I was aware of that (which is why I mentioned "all metacharacters") - but maybe it is confusing to include that in this answer - I'll remove it. – RedGrittyBrick – 2013-10-08T10:19:38.353

3

You can do the following:

find . -type f -name "*(*)*" -delete -maxdepth 1

For testing I would use the -print argument first:

find . -type f -name "*(*)*" -print -maxdepth 1

If you want to do it in all subdirectories you can ommit the -maxdepth 1

If the -delete does not work you can try:

find . -type f -name "*(*)*" -exec rm -rf {} \;

Edit: Included the -type f to only do this on files (and not directories) same as in rm.

Rik

Posted 2013-10-08T09:11:49.910

Reputation: 11 800