Friday, March 26, 2010

Grepping ip address accurately

Let's say we have one log file named logfile.log that contains a few lines like below:

192.168.1.1
192.168.1.10
192.168.1.11
192.168.1.111

When we want to search for 192.168.1.1, we usually will use:

$ grep 192.168.1.1 logfile.log
192.168.1.1
192.168.1.10
192.168.1.11
192.168.1.111

But unfortunately the result is not as what we expected(I assume we expect only 192.168.1.1 will come out) because grep will show to us all results "containing" the pattern given by us.

To overcome this problem, we have to use grep like this:

$ grep "192.168.1.1\>" logfile.log
192.168.1.1

Do not forget to put the double quotes, if not the command will not show any result.

That's all :)

Update:

Credit to sharuzzaman.blogspot.com for below technique, you can find the original post here

An alternative way to achive above result is by using -w flag of grep. So, instead of using grep "192.168.1.1\>" logfile.log, you can also use grep -w 192.168.1.1 logfile.log

No comments: