Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - How to extract IP address using sed?

Tags:

This is for an assignment so I have no choice but to use sed.

Given a file messages, how can I extract all the IP addresses and print them?

I first tried

sed -n '/((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])/p' messages

But it printed nothing. After doing some research, I found out that sed does not support non-greedy operators like ? and |.

I've been wracking my brain but I can't think of a way to do this without the non-greedy operators. How can I do this?

like image 730
MrDiggles Avatar asked Feb 18 '13 02:02

MrDiggles


2 Answers

grep will be more suitable there (if you have sed, you should have grep too):

grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' messages

This is your own regex with no modification (tested OK)

like image 88
Gilles Quenot Avatar answered Sep 17 '22 09:09

Gilles Quenot


If you have GNU sed, you could simply add the -r flag to use EREs:

sed -rn '/((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])/p' file

Otherwise, you will need to escape certain characters:

sed -n '/\(\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)/p' file

These characters include:

  • groups using parenthesis: (, )
  • occurrence braces: {, }
  • 'or' pipes: |
  • non-greedy question marks: ?

Generally (although not for your case) I use the following to match IP address:

sed -rn '/([0-9]{1,3}\.){3}[0-9]{1,3}/p' file

Or in compatibility mode:

sed -n '/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/p' file
like image 38
Steve Avatar answered Sep 21 '22 09:09

Steve