Sunday, December 9, 2012

You can't survive without 'grep' (most importent grep commands)

I started my internship in wso2 6-7 months ago. By then I had no clue about the Linux command prompt. Even though I have worked with Ubuntu in when I was doing my A/Ls I didn’t use the bash to anything at all. But with the start of my internship I started Using the Command line for almost everything. It is a one way stop for everything and you feel really powerful and feel more control over things. With those I moved towards using the Command line more and more. When I do that ‘grep’ played a big part in my life. Simply you can’t survive in a command line environment without ‘grep’. Below are some nice little commands using grep that I think everyone should know.
basic usage of grep command is to search for a specific string within a specified set of files. In below commands you have to replace the <> and what is in there with what you need.

grep "<string you need to search>" filename

e.g. grep “submitFilterForm” index.jsp
Here we are searching for “submitFilterForm” in index.jsp. This will return the sentence that string can be found (if there is any).you can give a file pattern instead of the file name

e.g. grep “submitFilterForm” *.jsp
And if you need you can replace the search string with a regex. You can use some parameters to make the search more advances.
  • i - Ignore case(ignore capital, simple, “the”, “THE” and “The” all will be same)
  • w - Full strings only (if you don’t use this all the substring matches also will be there in the search)
  • v - Negative search. ( When you want to display the lines which does not matches the given string/pattern)
  • n - Line numbers (To show the line number of file with the line matched. It does 1-based line numbering for each file. Use -n option to utilize this feature.)
e.g. grep -iw "submitfilter" *.java
Above will search for "submitfilter" as a full word, ignoring case insensitively within all java files, try it and you will understand more.
e.g. grep -i "submitfilter" *.java
Above will search for "submitfilter", ignoring case insensitively within all java files.
e.g. grep -v "submitfilter" *.java
This will search for places which do NOT match "submitfilter”, within all java files.