Find - a very useful tool
The GNU tool find is a very useful tool to be aware of when administering a linux/unix system. For a detailed information on find and two other tools locate and xargs read throught the find info page.
$ info find
I first came across find when I had copied a large amount of data from a WinNT box to a linux box and wanted to fix up permissions for the files that were scattered throughout the different sub-folders that were in the folder I had copied across. I had previously just done this sort of thing using chmod -R but you run into big problems with this command if you want to remove executable permissions from files as with chmod -R you would also remove execute permissions from folders which is not what you want. After racking my limited scripting skills for a while trying "for i in $(ls /...).." I gave up and posted a plea for help to the debian users list. In no time at all a number of people had pointed me to find and there was a nice discussion thread going on the merits of find and xargs between the people with knowledge.
Using the tips from the list and reading through the man and info pages for find I came up with this command that let me do what I needed to do with find and also let me fix up a few other problems such as bad file names certain users had created.
$ find /home/e-smith/files/ibays/original -type f -exec chmod a-x \{\} \;
To fix up some bad file names I used this command:
$ find /home/e-smith/files/ibays/original -regex '.*doc.*\.exe' -type f -exec rename .doc.exe .doc \{\} \;
Here is something that I used to a search and replace and a number of php and html files contained in a directory and various subdirectories:
find . -name 'flash' -o -name 'resources' -o -name '*.swf' -o -name 'images' -o -name '*.txt' -o -name '.listing' -o -name '*.pdf' -o -name '*.gif' -o -name '*.jpg' -o -name '*.doc' -prune -o -type f -print0 | xargs -0 perl -i.bak -pe 's|/images|images|g'
This basically goes through a directory and its subdirectories creating a list of all files, except those named to be pruned. This list is then passed to xargs which runs the perl command on them that creates a backup of the file and then replaces "/images" with "images" in the original file. If you don't want to create a backup copy of each file simply drop the "-i.bak" part of the perl command.
If you want to look at more ways of doing global search and replaces, for example you could open all files that match a particular pattern in vim and then do a search and replace using the "bufdo" command:
:bufdo %s/\/images/images/g
see this great thread on search and replace on multiple files http://mail.gnhlug.org/pipermail/gnhlug-discuss/2003-May/003814.html .
