Last updated on November 14th, 2015 at 11:41 pm
What is grep ?
‘grep’ is a line searcher specially its very helpful when you are dealing with large text files or even multiple files. Name ‘grep’ drives from unix/linux text editor eg: (global / regular expression / print) g/re/p.
How to Use Grep ?
1: A simple example of grep is to find the word ‘broexperts’ from /etc/passwd file. To make more sense, suppose you need to know that user broexperts is available on system or not. so in this case you will look /etc/passwd file which contains all the information related to system accounts.
grep broexperts /etc/passwd
Remember Linux Operating system is case sensitive in nature, so the output of this command will be based on the lines which contains the word ‘broexperts’. By default grep will show you case-sensitive words i.e ( broexperts.com, broexperts etc ).
2 : Ignore word case-insensitive. ‘ -i ‘
For expecting all words case sensitive you must provide the ‘-i’ option with your command. it will return case-insensitive results.
grep -i broexperts /etc/passwd
Above command will ignore case-sensitive words and in the output it will print the lines that contains word. i.e (broexperts, Broexperts, BroExperts.com etc ) respectively.
3 : Search only words. ‘ w ‘
You can specify ‘w’ option in grep command that will show you only the specified word.
grep -w ‘broexperts’ /var/log/messages
This options will generate the result according to specified word i.e (broexperts.com, dnsbroexperts, ftpbroexperts etc)
4: Search two different words with grep
egrep -w ‘david | mike’ /etc/passwd
5 : Recursively ‘ -r ‘
With ‘-r’ option you can search your word recursively in the each directory.
grep -r ‘broexperts’ /etc
6 : Count lines that contains specified word. ‘ -c ‘
grep -c ‘kernal’ /var/log/messages
‘-c’ option will match the lines that contains word ‘kernal’, in the output you can see counted numbers.
7 : skip the specified word using ‘ -v ‘ option.
you can use lower case ‘v’ option to force grep show the result except the specified word.
grep -v broexperts users_name.txt
Regular expressions :
Regular expressions can be used to analyze or match more complex text pattern.
8 : Search the line that ends with a specified word. ‘$’
grep ‘com$’ domain_names.txt
the above command’s output will print the lines that ends with ‘com’ from domain_names.txt file.
9 : Search the line that begin with a specified word. ‘^’