The command find is a powerful tool that can be used for many tasks that operate on a whole directory.
For example, you can find all Java source files in your home
directory (represented by the tilde ~
) with the following use of the find command.
[alice@onyx docs]: find ~ -name "*.java" -print /home/alice/.java /home/alice/CreateDataFiile.java /home/alice/ListFiles.java ...
However, note that it also matches the file named .java, which isn't a valid Java source file. We can skip that by insisting that the pattern must contain at least one letter before the dot. see below:
[alice@onyx docs]: find ~ -name "*[A-Za-z].java" -print /home/alice/CreateDataFiile.java /home/alice/ListFiles.java ...
Another example: you can find all files that were modified in your home directory in the last 30 minutes with the following use of the find command.
[alice@onyx docs]: find ~ -mmin -30 -print /home/alice /home/alice/.kde/share/config /home/alice/.kde/share/config/kdesktoprc /home/alice/.kde/share/apps/kalarmd /home/alice/.kde/share/apps/kalarmd/clients /home/alice/.Xauthority /home/alice/.viminfo /home/alice/public_html/teaching/handouts /home/alice/public_html/teaching/handouts/cs-linux.tex /home/alice/public_html/teaching/handouts/.cs-linux.tex.swp /home/alice/public_html/teaching/253/notes /home/alice/res/qct/pds/sect7/s7ods_orig.tex /home/alice/res/qct/pds/sect7/s7ods_hash.tex /home/alice/.alice-calendar.ics [alice@onyx docs]:
One of the most powerful uses of find is the ability to execute a command on all files that match the pattern given to find. Here are some examples:
find . -name "a.out" -exec /bin/rm -f {} \;
The characters {} represents a field that gets filled in by the pathname of each instance of a file named a.out that the command find finds. In the above we have to escape the semicolon so that the shell does not process it. Instead the find command needs to process it, as it represents the end of the command after the -exec flag.
find ~ -name "*.c" -exec chmod -x {} \;
find ~ -name "*.[c|h]" -exec chmod -x {} \;
The expression *.[c|h]
is an example of a regular expression. Regular
expression are a powerful way of expressing a set of possibilities. See man 7 regex for the full syntax of regular expressions.
find dir1 -type f -exec gzip {} \;
find dir1 -type f -exec gunzip {} \;