Using the Find Command Part 2

Hi to Jeremy from NZ who gave us some nice and constructive feedback on my blog of how to find and copy certain types of file in the command line, he thought it would useful to explain how find and copy works, so here goes.
Let’s start by looking at a quick comparison, as a Mac user you might ask why not use spotlight?
Spotlight lets me find stuff and then select some of the found items and copy them so why use the find tool?
As wonderful as Spotlight is, spotlight is a user tool, the index created by Spotlight is there to help users find the stuff they create therefore it excludes system stuff, as an IT guy I often need to find files that are not user created, the find tool used as root allows me search the whole disk.
So to remind you of the command I used…
sudo find / -name “*.jpg” -exec cp {} /Users/pete/jpegs ;
Firstly sudo, this allows a permitted user to run the following command as the root user or any other user as defined in the /etc/sudoers file.
The find tool recursively descends the directory tree for each path listed.
/ tells find where to start looking, in this case we are starting at the very top of the file system.
-name “*.jpg” This part of the command is what we are looking for and will find any file represented by * that ends with .jpg and only .jpg We could replace -name with -iname to make the search case insensitive so we can match files that end with .jpg .JPG or any mix of upper and lower case, I may also want to look for files that end with .jpeg or JPEG the following would include the additional files.
find / -iname “*.jpg” -o  -iname “*.jpeg”
The -exec parameter is what gives you the power of this command. When a file is found that matches the search criteria, find takes all arguments after -exec to be part of the command until an argument consisting of ; is reached. It replaces the string {} by the current file name being processed everywhere it occurs in the command.
In this case the -exec executes the cp command when a file is found, the following would be executed if the file amsys.jpg was found on my Desktop…
cp /User/pete/Desktop/amsys.jpg /Users/pete/jpegs/amsys.jpg
We can replace the cp with other commands to create all sorts of powerful commands but be careful if you are using something destructive, it is worth testing with ls to see what output you are going to get. We can also replace -exec with -ok to get the command to prompt you before executing the command.