Monday, August 27, 2012

rm -R with wildcard

Unfortunately, it seems the shell of Mac OSX doesn't support wildcard in 'rm -R' command. So if you want to delete, for example, some "*.swp" files which locates on many sub-directories, it will be very difficult.

However, there is a workaround by using the command "xargs". Here is the method:

$ find . | grep *.swp | xargs rm

What's the meaning?

First, "find ." will list all the files / directories in the current directory (.).
Then, the "|" will send the results to "grep", and grep will filter all the files/directories which don't meet "*.swp", that is, all the *.swp will be listed by "grep".
At last,  "xargs" will use the results returned by "grep" as argument for "rm", so that the file will be removed.