The grep is a Linux utility command which will help you in searching the contents within the file. It is the most useful when you are debugging through a large message file. It can be helpful in the scripts too. Let us see some Grep Command Examples.
Below are a few examples and the tricks for the grep command.
1. Grep Command to highlight Color
The below command will search for “DB Error” in the /var/log/messages and highlight it with red colour so you can quickly identify it.
$ grep --color "DB Error" /var/log/messages
2. Print 3 lines before and after the pattern match in grep
If you want to print the lines before/after the pattern matches then you can use the -A (after) or -B (before) option. The below command will print 3 lines before and after the match.
$ grep "DB Error" /var/log/messages -A3 -B3
3. Ignore Cases
If you are searching for a word from the file but you don’t know if the word is in a small case or upper case. In this case, you can use
-i option which will search for the word no matter how it’s written
$ grep -i "Justgeek" /var/log/messages
4. Search for the whole word.
By default, if you search for the word it will also search that string if it’s between a word. For example, if you search for a word then it will print the lines below.
$ grep -i "justgeek" file.txt JustGeekis Great justgeek is great
However, if you use
-w. then it will just look for that particular word.
$ grep -wi "justgeek" file.txt justgeek is great
5. Search for the lines ending with some words.
I have a file which has a list of the cities, along with their state code.
Pune, MH Nagpur, MH Mumbai, MH Bhopal, MP Lucknow, UP Agra, UP
I want to search for the cities in MH then you can use
$ as used in the command below.
$ grep MH$ ListOfCities.txt Pune, MH Nagpur, MH Mumbai, MH
6. Search for the words starting.
If you want to search for starting words/letters then you can use
$ grep ^P ListOfCities.txt Pune, MH
7. Exclude words from the search
There are times when you want to exclude the words instead of searching them. In this case, you will have to use the -v option. In the example below, we are excluding the city “Agra”
$ grep -v "Agra" ListOfCities.txt Pune, MH Nagpur, MH Mumbai, MH Bhopal, MP Lucknow, UP
8. Search multiple words
If you want to search for multiple words, then you will have to use the regex option in grep. It can be used by adding
-E. In the same example as above, we will search for two cities.
$ grep -E 'Pune|Agra' ListOfCities.txt Pune, MH Agra, UP
I hope you have also seen my previous post on PIP