Grep
command in Unix/Linux is the short form of 'global search for the regular expression'.
The grep command is a filter that is used to search for lines matching a specified pattern and print the matching lines to standard output.
grep [options] [pattern] [file]
The pattern is specified as a regular expression. A regular expression is a string of characters that is used to specify a pattern matching rule. Special characters are used to define the matching rules and positions.
'^'
and '$'
at the beginning and end of the pattern are used to anchor the pattern to the start of the line, and to the end of the line respectively.
Example : "^Name" matches all lines that start with the string "Name".
'.'
Is used to match any character.
Example : "^.$" will match all lines with any single character.
'\'
.
Example: "$*" will match the lines that contain the string "$*".
'['
and ']'
pair specify a range of characters to be matched.
Example: "[aeiou]" will match all lines that contain a vowel. A hyphen
can be used while specifying a range to shorten a set of consecutive characters. E.g. "[0-9]" will match all lines that contain a digit. A carat
can be used at the beginning of the range to specify a negative range. E.g. "[^xyz]" will match all lines that do not contain x, y or z.
'*'
after a character or group of characters is used to allow matching zero or more instances of the preceding pattern.
-i:
performs a case-insensitive search.
-n:
displays the lines containing the pattern along with the line numbers.
-v:
displays the lines not containing the specified pattern.
-c:
displays the count of the matching patterns.
-h:
Display the matched lines, but do not display the filenames.
-l:
Displays list of a filenames only.
-e exp:
Specifies expression with this option. Can use multiple times.
-f file:
Takes patterns from file, one per line.
-E:
Treats pattern as an extended regular expression (ERE).
-w:
Match whole word
-o:
Print only the matched parts of a matching line, with each such part on a separate output line.
$ grep "^hello" file1
$ grep "done$" file1
$ grep "[a-e]" file1
$ grep "[^aeiou]" file1
$ grep -i "hello"
$ grep -v "unix" file1
$ grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" file1
If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.