Wednesday, May 8, 2013

Newbie help: find basics

The find command is a general file-finding utility with much a much broader range of talents than locate.  Find starts from a given directory and locates all files below that directory that meet specified constraints.  You can look for files by name (or regex), size, age, ownership, permissions, or any combination.

Find has built-in actions, such as delete, ls, print[ to file], and exec[ute-another-command].  You can also pipe the output into other commands.  I'll cover actions in a later post.

Basic syntax:
find path -constraint value

Add as many constraints as you like.   Any flag can be negated with a bang; see the very last examples for the syntax.

The most common constraints are size, and modified date (-mtime).  Both of these flags can serve as an upper or lower bound.

Example:  Which files below the current directory are less than five days old and more than 5kb?  Which are more than five days old and less than 5kb?

find . -mtime -5 -size +5000
find . -mtime +5 -size -5000

The -type flag allows you to specify whether you're looking for files or directories.  By default, find returns both.  Depending on your OS, the values will be either "f" or "file", and either "d" or "dir".  Check man for details.

The -name flag can take a full case sensitive filename, or a regex pattern.  If you use a pattern, enclose it in double quotes.

find /app -name applog
find /app -name "*log"
find . -name "*dunno*"
find . -name "[j,J]ava*"

Find can also identify files owned by a specific user or group.  (This flag is available on OS X, but doesn't appear to work.)

find /tmp -user kexline

Combine flags to ask real-world questions about your files.  Example:  What largish, non-gzipped  files did I create in my application directory since this time yesterday?

find /app -type f -mtime -1 -user kexline -size +100000 ! -name "*gz"

As promised, there's a bang negation.  Any flag can be prepended with a bang to reverse its meaning.  What files did all the other non-root users create yesterday, anywhere on the machine?

sudo su 
find / -type f -mtime -1 ! -user kexline ! -user root 

No comments: