AIX Tip of the Week

Finding Files Containing a String

Audience: AIX Administrators

Date: December 10, 1999

Here's a useful technique for searching for files in all subdirectories which contain a specific string.

find . -type f -print | xargs -i grep -il "searchstring" {}

where:
"searchstring" is the desired search string
"find . -type f -print" lists all files in the current directory and it subdirectories
"xargs" feeds the file names from the pipe into the grep command at the curly braces {}
The "grep -il" lists the files containing the "searchstring" (-i = case insensitive)

I use this command to find files on a web site that contain references to specific URL. Another variation would be to replace all occurrences of "searchstring" with another string by changing the "grep" to "sed" command. To save typing, put this command in a shell script.

#!/usr/bin/ksh
# Script name:  locate
find . -type f -print | xargs -i grep -il "$1" {}

To run, type locate searchstring, where searchstring" is the name of the search string.