On the command line (in Linux, for example), this isn't so easy.
Today I needed to clear out all Wordpress themes in a blog, except for the one currently in use.
How did I do it?
cd /var/www/mywordpresssite/wp-content/themes/
rm -rf `ls | grep -v themetokeep/ | grep -vF \.`
The above command removes all files and directories EXCEPT themetokeep, and those with dots in them. The latter is VERY important. If you include '..' in the rm-rf command, it will attempt to delete everything up one directory as well. In this case, that would have been the wp-content/ directory - yep, not a good idea!
Let's break that command down a bit:
ls
- the simplest way to list files. It just lists the names (no file size, dates, etc) of all files and directories in the current directory. Some systems are configured to hide the . and .. directories when ls is used with no parameters. However, some are not - which is why we need to be careful by adding that last grep.
|
- the pipe directs the output from one command to the input of another. In this case, we are sending the output of the ls command to the grep command, instead of printing the ls command's output to the shell.
grep -v themetokeep/
- grep - a great program that applies regular expressions to any input you give it, and outputs the result. It is essentially a filter.
- We are using the -v parameter to invert the match. This means we want to output all files and directories that do NOT have the name themetokeep/
If we didn't include -v and simply types grep themetokeep/ then we'd get an output list which only includes that directory.
grep -vF \.
- So now we have the output of the ls command, filtered to exclude the directory themetokeep/, and now we are filtering it one more time to remove the . and .. directories.
This is really important because we don't want to delete the current directory (wp-content/themes/) and we DEFINITELY don't want to delete the parent directory (..) - as this would remove all our plugins, cache, uploads, etc.. Please don't make that mistake as I once did! :)
- The -F parameter - to be honest, I am not exactly sure why we need this, except that if we don't use it, we won't be able to match the directories with dots in them. So use it.
- We put the slash before the . so that it is treated as a literal dot, and not the regular expression match character, which means 'any character'
rm -rf `...`
- rm - the delete command. We need -r to allow us to delete directories (and all their subdirectories). We need -f to suppress the 'Are you sure?' prompts. In other words, we're telling rm to delete everything we tell it - no questions asked.
- We put the filtered file list within the backticks ``, so that the file list becomes the instruction to rm.
Hope that helps you - any questions - leave them in the comments!
No comments:
Post a Comment