Friday, December 23, 2011

grep: Finds a String


The grep (global regular expression print) utility searches through one or more files to see whether any contain a specified string of characters. It does not change the file it searches but simply displays each line that contains the string.

Originally this utility's name was a play on an ed—an original UNIX editor, available on Linux—command: g/re/p. In this command the g stands for global, re is a regular expression delimited by slashes, and p means print.

Example

$ cat memo

Helen:In our meeting on June 6 we discussed the issue of credit.Have you had any further thoughts about it? Alex

$ grep 'credit' memo

discussed the issue of credit.

The grep command above searches through the file memo for lines that contain the string credit and displays a single line that meets this criterion. If memo contained such words as discredit, creditor, or accreditation, grep would have displayed those lines as well because they contain the string it was searching for. The –w option causes grep to match only whole words. You do not need to enclose the string you are searching for in single quotation marks, but doing so allows you to put SPACEs and special characters in the search string.

The grep utility can do much more than search for a simple string in a single file.


No comments:

Post a Comment