GREP is a command line search utility or tool to filter the input given to it. Grep got its name from ed editor as g/re/p (global / regular expression / print). Grep command can improve a command output by filtering out required information. Grep will become a killer command when we combined it with regular expressions. In this post we will see how to use grep in a basic way and then move on some advanced and rarely used options. In our next couple of posts we will see what grep can do with the help of regular expressions.
GREP command syntax
grep [options] [searchterm] filename
command | grep [options] [searchterm]
Before starting grep command examples, I used below file which contain following content.
surendra 31 IBM ChennaiSteve 45 BOA LondonBarbi 25 EasyCMDB ChristchurchMax 25 Easy CMDB ChristchurchNathan 20 Wipro NewyarkDavid 20 ai Newyark
Search single file using grep
Example 1: Search for a word â€œnathanâ€ in file1.txt
grep nathan file1.txt
You dont get any output, as the word nathan is not there. By this type you should know grep is a case sensitive command. If you want specifically Nathan, use caps N in nathan and try once again.
Example 2: Search for exact word â€œNathanâ€
root@linuxnix:~# grep Nathan file1.txt Nathan 20 Wipro Newyark
Example 3: Search for a word which has either capital or small letters in it, no confusion between nathan or Nathan. The -i for ignore case.
root@linuxnix:~# grep -i Nathan file1.txt Nathan 20 Wipro Newyark
Example 4: I suggest you always use single quotes for your search term. This will avoid confusions to gerp. Suppose if you want to search for â€œEasy CMDBâ€ in a file, it will be difficult to search with out single quotes. Try below examples.
with out quotes:
root@linuxnix:~# grep Easy CMDB file1.txt grep: CMDB: No such file or directory file1.txt:Barbi 25 EasyCMDB Christchurch file1.txt:Max 25 Easy CMDB Christchurch
What grep did?
If you observe, you got an error stating that, there is no file called CMDB. That is true, there is no such file. This output have two issues
1) Grep is considering second word in the command as file
2) Grep is considering just â€œEasyâ€ as a search term.
Example 5: Search for exact search term using single quotes.
root@linuxnix:~# grep 'Easy CMDB' file1.txt Max 25 Easy CMDB Christchurch
You may get a doubt why single quotes and not double quotes. You can use double quotes as well when you want to send bash variable in to search term.
Example 6: Search for a shell variable in a file. My shell is NAME1 which is assigned with Nathan. See below examples with single and double quotes.
Read Full Post: http://www.linuxnix.com/grep-command-usage-linux/