Find is unquestionably useful in many situations. I used it for example in my previous post for the backup with tar. There are a few things which I would like to mention here, because they are a bit tricky to find, or especially useful.
You can limit the search to certain types. The different types find knows about it are
If you just want to find one of these types, you can simply use
$ find /dir/to/search -type f
This finds all regular files in the /dir/to/search. If you want to combine them, use ‘-or’
$ find /dir/to/search -type f -o -type l
Which will find all regular files and symbolic links in the /dir/to/search. If you need the print0 command, don’t forget to put -print0 after every type. print is used by default, unless you specify it explicitly. In that case, it will only be used where you have specified it. Here’s the same command, but using print0 and xargs
$ find /dir/to/search -type f -print0 -o -type l -print0 | xargs -0 do.something
Use the or operator to do this. You can either exclude directories or files based on there name or based on the path. The latter is preferrable. You could also use exclusion based on the type (e.g. exclude all symbolic links, etc.). Here’s an example of how to use it when excluding directories DIR1 and DIR2 based on their names.
$ find /dir/to/search \( -name DIR1 -o -name DIR2 \) -prune -o -print
Here’s the same example, but directories are excluded based on their path
$ find /dir/to/search \( -path /path/to/DIR1 -o -path /path/to/DIR2 \) -prune -o -print
If you want, for example, remove all files ending on .mp3 in your home directory, you could use
$ find . -type f -iname "*.mp3" -exec rm -f {} \;
Be careful, if executed, this command will actually remove your mp3 collection in your home directory! Another way of doing this is to take xargs instead of -exec. This has the advantage that only one remove command would be executed. If you use the -exec version from above, the shell will execute the remove command for every file which is found by find. Therefore, xargs is preferrable if you have to deal with many files.
$ find . -type f -iname "*.mp3" -print0 | xargs -0 rm
Sort the output of a find command to see a list of filenames that are unique (duplicate entries are omitted). The example searches in the current directory for all files ending in .conf and sort the list to omit multiple entries. Since sort defaults to reading standard input, the sort command can be written as sort -u only.
find . -iname "*.conf" -printf "%f\n" | sort - -u