Unix How-To: Making Better Use of Find

Find is not just useful for locating files, but also for doing things with the files once it finds them. You can find files based on numerous criteria -- their names, their owners, their size, etc. -- and you can then perform some operation on the files from simply listing them to changing permissions or analyzing their contents. You can also make the operation that you specify to occur only if you confirm that you want it to happen after you are prompted. Let's see how this works.

The most standard use of the find command seeks to locate files based on some simple parameter such as their names, owners, size, etc.

find . -name *.sh
find / -user jdoe
find . -mtime -1

You can also pass the list of found files to some other utility using find's -exec clause, xargs or some other tool.

find . -name *.sh -exec chmod g+x {} \;
find / -user jdoe >> /tmp/jdoe.files
find . -mtime -1 | xargs chmod g+r

The {} specification in the first command is replaced for each iteration of the chmod command by the found file's name.

You can, however, elect to take action on each found file on a case by case basis. Using the -ok parameter, the find command will take the action specific (the "head -1" command in the example below) only if you confirm by typing "y" or "Y" at the prompt.

$ find . -type f -ok head -1 {} \;
< head ... ./dir1/file1 >?   n
< head ... ./dir1/file2 >?   n
< head ... ./dir2/file1 >?   y
This file contains a listing of all participants in the August 2010 retreat.  Note that all

In other words, the -ok option takes the place of the exec command and adds the behavior of prompting the user for a response of whether to proceed with the action specified. This can be useful if you, for example, want to avoid counting lines or grepping on the contents of binary files.

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.
Take IDG’s 2020 IT Salary Survey: You’ll provide important data and have a chance to win $500.