In our the 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 the 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 the example, it will be there for a long time in our mind. Now we will see one example each regular expression what we have given above.

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

grep ‘^Mr’ filename

Example2: Find all the lines which end 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 blank lines in the output.

Related concept:   RPM Package Management - I

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

grep ‘ba*s’ filename

The above grep command will search for words which have a between b and s zero or more times.

Example5: Search for all words which start 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 three 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 regular grep we have to use escape character () to negate it. So use ‘[‘ to search for [. This is applicable for all the special characters mentioned 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.

Related concept:   7 Grep command examples with extended regex in Linux/Unix