Grep and find - Finding files on your computer

From Cosmin's Wiki

Jump to: navigation, search

Home > Linux how to's > Grep and find - Finding files on your computer


grep - Finding files by content

One of the most common usages I have met for grep is to find files containing a given search pattern, starting from a certain point in the directory structure.

> grep -irl "test me" .
This will search recursively in the current directory and all its subdirectories for all files containing the string "test me", case insensitive, and will display only the files which have a match.

One slight variation of this is when you want to search only certain file types. In this case use:

> grep -irl --include="*.php" "test me" .

find - Finding files by name

Another quite big issue is to find files by name on your system. To retrieve for example all files which contain in their name the string 'cos' (case insensitive), recursively starting from the /var/www directory, type

> find /var/www -iname *cos*

The more complex version of finding files by file-name-pattern is to use regular expressions:

find /var/www -regex '.*_20110[5|6].*'

will find all files under /var/www containing _201105 or _201106. Pay attention however, that the regular expression applies to the full path of the file, not only the current file name

Execute something on each file returned by find

Another very nice feature is to execute some commands on all files returned by find. For example, we want to have a full listing of the files in the example above. For that we do:

find /var/www -regex '.*_20110[5|6].*' -exec ls -lh '{}' \;

Here, pay attention to the following:

1. '{}' stands for "every result of the find statement"
2. Pay attention to the spaces before and after '{}'
3. \; ends the exec statement