SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Monday, November 26, 2007

Grep Command

What is Grep?


Grep stands for "Global Regular Expression Print". It is the universal Unix command to extract specific patterns out of strings using regular expressions. (The word grep also comes from the vi/ex command to print all lines matching a certain pattern

g/re/p


where "re" is a "regular expression".)

Grep and its Uses


To search a text file for a string of characters or a regular expression use grep as follows:


grep pattern filename(s)

Using this command you can check to see if a text file holds specific information. grep is often used to search the output from a command.


The following are the most commonly used options of the grep command.



  • -i Ignore the case of the letters when searching the file.

  • -n Output the line number of each line where a match is found in addition to the line itself.

  • -v Output all the lines that DO NOT contain the search-string.

  • -w Output all the lines that contain the word being searched for.


Examples


a) Search for all the occurrences of the string able in the file Chapter1.txt.


grep able Chapter1.txt

b) Search for all the occurrences of the string able in the file Chapter1.txt, ignoring the case of the letters in making comparisons.


grep -i able Chapter1.txt

c) Search for all the occurrences of the string able in the file Chapter1.txt. Output the line number of each line where a match is found in addition to the line itself.


grep -n able Chapter1.txt

d) Output all the lines that DO NOT contain the string able in the file Chapter1.txt.


grep -v able Chapter1.txt

e) Output all the lines that contain the word able in the file Chapter1.txt.


grep -w able Chapter1.txt

f) Output all the lines that contain the string was able in the file Chapter1.txt.


grep 'was able' Chapter1.txt

g) All of the previous examples can be made applicable to a group of files by using the star convention. The following searches for the string able in all the files whose names start with Chapter.


grep able Chapter*

The string you are searching for can be more than one word (i.e. there is a space or other delimiter character such as a comma or a hyphen in the string). In such cases, single quotes (') may be placed around the string. It is also useful to know that the string is treated as a regular expression resulting in characters such as . and * having special meaning.