Tuesday, December 16, 2008

Moving Files in Linux BASH

Here's a great example of the power of the command line interface in Linux. In my case and probably most of your systems I'm using BASH as my CLI.

I recently used the all powerful wget command to mirror a rather large database of images from an undisclosed location on the web. This website had almost 4000 clipart images that I really wanted to add to my collection for web design etc. Anyhow the issue was going through the website one by one and saving the files would have killed me. Just not practical so I just recursivly retrieved 5 levels deep of the clipart which incidentally was located in hundreds of sub folders labelled as per the content... Example: www.site.com/images/cars, www.site.com/images/plants etc... You get the idea... So now I have a mirrored site with a problem, how to get all those handy little .jpg and .gif files moved into a single directory that I could peruse on my own terms.

PROBLEM: Thousands of .jpg exension files in hundreds of subdirectories.
SOLUTION: Use some BASH commands... In this case FIND and MV.

The syntax I used looks like this;

find /websitedir/ -name "*.gif" -type f -exec mv {} /onlyimages/ \;

OK so lets break this down... The find command is being told to look in directory /websitedir/ for files named *.gif the * is a wildcard so it means find anything with the .gif extension. Then the second switch -type f tells find that it is a file it's looking for and not a directory. When it finds the files -exec invokes the mv (move) command recursively to copy the said files to the new directory /onlyimages/ then it ends with \;

The result is a directory called /onlyimages/ that is filled with all the images from those hundreds of subdirectories that are in the original find dir...

Fantastic eh?

No comments:

Post a Comment