Monday, 29 March 2010

Alternative way to grep IP address accurately from log file

This post is an alternative way to grep IP address from log file, as a reply for Hisham Mohd Aderis (linuxwave) post.

Let say we have a log file that contain IP address as below

$ cat ipadd.txt

If we use just grep to get, all the IP address will be returned. This is because the default setting for grep regular expression is greedy, which means that it will match anything that have full or part of the string that we are searching for.

$ grep ipadd.txt

But, grep got a "-w" switch that will match only the word that we are looking for.

       -w, --word-regexp
              Select  only  those  lines  containing  matches  that form whole
              words.  The test is that the matching substring must  either  be
              at  the  beginning  of  the  line,  or  preceded  by  a non-word
              constituent character.  Similarly, it must be either at the  end
              of  the  line  or  followed by a non-word constituent character.
              Word-constituent  characters  are  letters,  digits,   and   the

So, to match an IP address correctly, we should use the command as below

$ grep -w ipadd.txt

$ grep -w ipadd.txt

As shown, the IP address will be matched to the one that we are looking for.

Happy scripting. :)

No comments:

Post a Comment

Please write your comment about this blog post. Thanks! :)