Find

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

I love find, and I use it all the time. I use a fair number of its features.

When I am looking for a file named "something-foo-something", I do this:

$ find -type f "*foo*"

If there are symlinks I want to follow, I will use the '-follow' parameter:

$ find -follow -type f "*foo*"

Sometimes I am lazy and I drop the -type f part.

If I am looking for a directory named "something-foo-something", then I use -type d:

$ find -type d "*foo*"

Or I get lazy and drop the -type d part as well.

If I want to do something to the files I find one at a time, I will use -exec.

$ find -type f "*.bak" -exec rm {} \;

The {} bit is the filename of the thing we found, and the \; bit says "that's all for the command I want to exec.".

If I want to do something to a bunch of files at once, I use xargs.

$ find -type f "*.py" | xargs svn add

But sometimes there are too many files and xargs complains. So I do something like this:

$ find -type f "*.py" | head -100 | xargs svn add

I run that command a lot until there is nothing more to run. I could probably put it into a shell loop, but it is easy enough to go up one step and hit CTRL-D a lot.

Sometimes I want to find files older than 5 days:

$ find -type f -ctime +5

Or sometimes I want to find files owned by the user 'foo':

$ find -user foo

Finding Files With Permission Bits Set

Let's say I'd like to find all the files and directories with the permission bits that allow groups and other to write to that file set.

$ find -perm -go+w

Or sometimes I want to find files that are writable to the user but not the group:

$ find -perm -u+w -not -perm -g+w

These are the most common patterns I use. Enjoy!