How To Use grep Command In Linux / UNIX

Originally published at: https://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/

How do I use grep command on Linux or Apple macOS/OS X? How can I use grep command on Unix operating systems? Can you give me a simple examples of the grep command?

You want to find any line in a file which contains a string. With system administration, you’ll do this quite a bit with log files, for example I might want to figure out either, what system is getting an address from my DHCP server, or maybe I have the MAC address of a computer and I want to find out if it’s communicated with my DHCP server.

$ grep 00:0c:0f:fe:e0:00 /var/log/dhcp.log
$ grep '192.168.1.101' /var/log/dhcp.log

Or, you might want see what processes on your computer are using port 80 (http), whether it be communicating in, or out.

$ netstat -pantu | grep ':80 '

Maybe you have a service with information you can query, but it gives more info than you need. For example, ‘finger’ give a bit of information from several sources, but you only need one bit. This one involves some other commands. (Note: nixcraft isn’t allowing me to even put sample email addresses into this response, so where I say “valid-email-address” this would be an actual, valid email address)

$ FULLNAME = `finger valid-email-address | grep -iA1 "also known as" | tail -1`

With this one, you’d have to know that where you’re searching, the finger command would, in part, list a user’s entry like this:
$ finger valid-email-address
“loginname, People”
Also Known As:
Joe S User
Joe Sample User
Affiliation:
Marketing
E-Mail Address:
valid-email-address
etc…

The ‘-i’ in the grep command tells grep to ignore case, so “KNOWN” is the same as “known”.
The ‘-A1’ in the grep command tells grep to also give the line after whatever you’re searching for.
Then ‘tail -1’ will give only the last line of the results.

You can also search for everything except something by using ‘-v’. The ifconfig command will report on network adapters. ‘ifconfig -a’ will give you all the information on all of the network adapters. Maybe you only want to know what all of the network adapters are called. You can use something like this:

$ ifconfig -a | grep -v '^ '

This will eliminate any results where a line starts with a space. “^” == beginning of line. You could also search for something at the end of a line using “$”, as such:

$ dig google.com | grep 'msec$'

Which will query DNS for info on google.com and the grep statement will only show you how long it took for the server to get you the results.

what if my search file looks like this:

file1.txt
1.txt
1.txt.bak

and I want to search for “1.txt”?

With this command: grep “1.txt”, I got the three lines as output. but I only want to search 1.txt exactly. I want the second to be my only output