grep

From Initq

Jump to: navigation, search

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.

Function and usage

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

 g/re/p

This command searches a file globally for lines matching a given regular expressions, 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.

The option -e can also be used to declare multiple patterns for searching on the command line with some versions of grep.

Look for the work network in all the initialization files recursively.

 [root@ohnonono etc]# grep -r network /etc/init.d/

Look for files

  • grep -l EMAIL *

Will print only the files name that has EMAIL in it.

Personal tools