2

I have a big report with many IP address shown in random lines. All the IP address start out with 192.168. I would like to extract only the Ip addresses and get a report that looks like:

192.anything.anything.anything

192.xx.xx.xx

192.xx.xx.xx

And nothing else. I tried cat filename | grep -w 192 that seems to get the whole line. I only want the full IP address. I appreciate any information you can share with me.

  • 1
    Now the addresses start with 168 or 192? Or 192.168? Also there is another cat abuse. Just grep pattern filename. – ott-- Aug 13 '15 at 19:10
  • All the addresses start with 192.168 – tester787 Aug 13 '15 at 19:16
  • @tester787: You've made a mistake in your question.  Don't use comments to say what you meant; edit the question and fix it. – Scott Aug 13 '15 at 19:51
  • Are all of the IP addresses followed by a space? Also, read this page, especially example #3. – WAF Aug 13 '15 at 20:09
7

I do this with egrep -o or grep -E -o

The -E flag in grep activates regex (which is what egrep does by default), and the -o flag prints only the matching string.

grep -E -o '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' /path/to/log
192.168.1.11
3
grep -o '192.168.[0-9.]*' datfile | sort -u

May not be portable to ancient versions of grep, but -o seems to be in both GNU and *BSD grep, so... (it's also not a perfect match on a IP address, but doing the proper number ranges with regex is super annoying.)

1
sed -n 's/.*\(192.168.[^ ]*\).*/\1/p' filename

should do the trick. \> indicates end of word.

  • Did you mean to include the p flag? And it doesn't work the way I'd expect, at least not with ifconfig output. – drewbenn Aug 13 '15 at 19:40
  • Can you try now? – unxnut Aug 13 '15 at 20:03
  • Thank you very much every one, I am good to go. I appreciate it. – tester787 Aug 13 '15 at 20:32
0

As all the IP addresses start with 192.168. you can do:

grep -o '192\.168\.[^ ]\+' file.txt

For example :

$ grep -o '192\.168\.[^ ]\+' bar.txt 
192.168.5.4
192.168.1.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.