Tuesday, April 14, 2009

Finding files and files that contain some string

How to find files is a very basic thing to know on a unix system. Fortunately it's very easy using the find command. Here's an example of how to use the find command to find log files for instance: 

find . -name '*.log' -print

This will look through all the directories using the current directory as the root for files that match the pattern *.log. It will print them out with paths relative to the root. for example the output of the command above might look like this:

./dir1/dir2/access.log
./dir1/dir3/dir4/temp.log
./dir5/dir6/error.log

If you put the full path to the root in the find command like this:

find /home/users/jsmith -name '*.log' -print

The out put will look like this:

/home/users/jsmith/dir1/dir2/access.log
/home/users/jsmith/dir1/dir3/dir4/temp.log
/home/users/jsmith/dir5/dir6/error.log

Now let's say that you want to find only files that contain a particular string.
This is relatively easy thing to do. Here's one way to do it, I'm sure there are more.

find . -name '*.*' -exec egrep -l -e 'string to find' {} \;

This will give you a list of file names. To see the actual line in the file remove the -l switch.

Click here to see more info about egrep.


Commands used in this post: find, egrep 

No comments: