Tuesday, March 12, 2019

GREP unix command useful tips!!!

Recently I learned  useful tips from my manager for 'grep' which helps a lot when troubleshooting the  issues with logs. In this post I will explain about below

  • How to search multiple strings in a file at the same time.
  • How to display found string in the color.
  • How to exclude particular string in the search result
  • How to display total no.of lines in the grep result


Search a string in a file using grep: Check this link for basic usage  of grep command.  
Lets see this tip with example. Below is the content of a file demo.txt and this file name we are going to use in this example as well.




How to search multiple strings in a file:
In the below screen we are search for the strings 'demo', 'show' and 'multiple' in the file demo.txt and and the result is as follows.


How to display found string in color:
In the above screen, even though grep found the patterns, it is difficult to identify in which line these patterns available. For that you can use grep command property 'color' as shown below.



From the above screen, we can easily identify the found strings as they are highlighted in red color. This color utility will save lot of time when you are searching in debug logs while troubleshooting.

How to exclude particular string in the search result: GREP command will supports option to exclude particular pattern from the result. This is basically not including a string in the result.



In the above screen, initially search for the strings 'demo' and 'show' and in the results I want to exclude the string 'multiple'.

How to display total no.of lines in the grep result: We can use -c option to get the total number of lines of the grep result. If the pattern is unique in each line, that count will be total no.of occurrences of the pattern.



In the above screen, searching for the patterns 'demo' and 'show' results two lines and using -c option will show the total count to two. If the grep results are more, this count option will be very useful.


Happy Learning!!!

No comments:

Popular Posts