

Friday, May 30, 2008

Solaris grep -r alternative

As per wikipedia, grep (Global Regular Expression Print) is a command line utility that was originally written for use with the Unix operating system. Given a list of files or standard input to read, grep searches for lines of text that match one or many regular expressions, and outputs only the matching lines.

The program's name derives from the command used to perform a similar operation, using the Unix text editor ed:

This command searches a file globally for lines matching a given regular expression, and prints them.

There are various command line switches available when using grep that modify this default behavior including printing lines which do not match, finding or excluding files to search, and annotating the output in various ways. There are also multiple modern implementations of the classic Unix grep, each with a unique feature set.

This is an example of a common grep usage:

 grep apple fruitlist.txt 

Grep would return, in this case, all of the lines in file fruitlist.txt with at least one instance of 'apple' in them. Keep in mind that grep would not return lines with 'Apple' (capital A) because by default grep is case sensitive. Like most Unix commands grep accepts flags which can be used to change this and many other behaviors. For example:

 grep -i apple fruitlist.txt 

This would return all lines with the words 'apple', 'Apple', 'apPLE', or any other mixing of capital and lower case.

Linux has a -r switch in grep command to search for a string in all the files in a directory tree. In Solaris you can use this command to do the same:

find . -type f -print | xargs grep -li "find me"

1 comment:

paluh said...

Grep doesn't print names and matches together when you search only one file. To achieve this effect you can add dummy arg (for example /dev/null) so the search command will print 'file_name':' matched text'. This can be done with:

find . -type f -print | xargs grep "find me" /dev/null


find . -type f -exec grep "find me" '{}' /dev/null \;