Friday, February 6, 2009

Deleting files/folders with the same name characteristics in Linux

I was trying to delete the .svn folders from a project in my linux machine and I had two options of doing that. Going folder by folder and find those .svn folders, which were about 20 or delete them all with one line of command connected by a pipe "|".

Here goes the trick and the explanation will follow it.

find /path/projectFolder -type d -name '.svn' | xargs rm -rf

Notice that we start this batch of commands with the find command. The find command takes 3 arguments. The find command will go through all directories and subdirectories starting from the path specified.

The first argument is the path to the folder where you want to perform the lookup of the file/folder. That's pretty straight forward

The second argument is the option "-type" where you define whether you are looking up a file or a directory. In the example given above I defined the type as being a directory. If I wanted to do a lookup for a file I would have an "f" there rather than a "d".

The third argument is the option "-name" where you define the name of the file or folder you want to look for enclosed by single quotes. You can also use wildcards in the name.

The second command I want to talk about is the rm -rf. This command removes all folders that are empty or has something in it.

Now here comes the trick. Every line that the find command returns is passed in to rm -rf through | xargs.
Now, having that in mind if you read from right to left this line commands should make more sense to you.

Google the commands find and xargs to see some cool stuff that you can do with them.

Hope this helps!

No comments: