Regular Expression in grep
Last Updated :
30 Jan, 2019
Improve
Prerequisite: grep
Basic Regular Expression
Regular Expression provides an ability to match a "string of text" in a very flexible and concise manner. A "string of text" can be further defined as a single character, word, sentence or particular pattern of characters. Like the shell’s wild–cards which match similar filenames with a single expression, grep uses an expression of a different sort to match a group of similar patterns.- [ ]: Matches any one of a set characters
- [ ] with hyphen: Matches any one of a range characters
- ^: The pattern following it must occur at the beginning of each line
- ^ with [ ] : The pattern must not contain any character in the set specified
- $: The pattern preceding it must occur at the end of each line
- . (dot): Matches any one character
- \ (backslash): Ignores the special meaning of the character following it
- *: zero or more occurrences of the previous character
- (dot).*: Nothing or any numbers of characters.
Examples
(a) [ ] : Matches any one of a set characters-
$grep “New[abc]” filename
It specifies the search pattern as :Newa , Newb or Newc
-
$grep “[aA]g[ar][ar]wal” filename
It specifies the search pattern asAgarwal , Agaawal , Agrawal , Agrrwal agarwal , agaawal , agrawal , agrrwal
-
$grep “New[a-e]” filename
It specifies the search pattern asNewa , Newb or Newc , Newd, Newe
-
$grep “New[0-9][a-z]” filename
It specifies the search pattern as: New followed by a number and then an alphabet.New0d, New4f etc
-
$grep “^san” filename
Search lines beginning with san. It specifies the search pattern assanjeev ,sanjay, sanrit , sanchit , sandeep etc.
-
$ls –l |grep “^d”
Display list of directories only -
$ls –l |grep “^-”
Display list of regular files only
-
$grep “New[^a-c]” filename
It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’ -
$grep “^[^a-z A-Z]” filename
Search lines beginning with an non-alphabetic character
$ grep "vedik$" file.txt(f) Use . (dot): Matches any one character
$ grep "..vik" file.txt $ grep "7..9$" file.txt(g) Use \ (backslash): Ignores the special meaning of the character following it
$ grep "New\.\[abc\]" file.txt
It specifies the search pattern as New.[abc]-
$ grep "S\.K\.Kumar" file.txt
It specifies the search pattern asS.K.Kumar
$ grep "[aA]gg*[ar][ar]wal" file.txt(i) Use (dot).*: Nothing or any numbers of characters.
$ grep "S.*Kumar" file.txt