In our previous post we saw how to use grep to search for words and played across different options. In this post we will see how to use Basic regular expressions to increase the power of grep command.

Basic regular expressions:

^ -- Caret symbol, Match beginning of the line.

$ -- Match End of the line

* -- Match 0 or more occurrence of previous character

. – Match Any single character

[] – Match Range of characters, just single occurrence.

            [a-z] –Match small letters

            [A-Z] –Match cap letters

            [0-9] – Match numerical.

[^] – Match Negate a sequence

 -- Match Escape character.

If we learn any new thing with example, it will be there for long time in our mind. Now we will see one example each regular expression what we given above.

Example1: Find all the lines which start with “Mr”

grep ‘^Mr’ filename

Example2: Find all the lines which ends with ‘sh’

grep ‘sh$’ filename

Example3: Display all the lines in a file expect empty lines.

grep –v ‘^$’ filename

Note:-v option is used to negate the search term, here ^$ indicates empty line, so our grep –v is filtering empty lines in the output.

Example4: Search for words which are bash, baash, bsh, baaash, baaaaash,

grep ‘ba*s’ filename

This will search for words which has a between b and s zero or more times.

Example5: Search for all words which starts with b and h

grep ‘b.*h’ filename

Example6: Search for a word which is having three letters in it and starts with x and ends with m.

grep ‘x[a-z]m’ filename

This search will return all the 3 letter words which start with x and ends with m.

Example7: Search words do not contain ‘ac’ in a file.

grep ‘[^ac]’ filename

Example8: Search for a ‘[‘ in a file

Note: The “[“is a special character, you cannot search with normal grep we have to use escape character () in order to negate it. So use ‘[‘ to search for [. This is applicable for all the special characters mention above.

grep ‘[’ filename

Please feel free to comment on this, if you have more thoughts. Stay tuned to our next grep post on how to use extended regular expressions.