unixsedgrepshnetbsd

Replacing IP addresses and spaces


I'm trying to transform ifconfig -a to give specific output but I am not sure whether sed is performing well. There is a possibility that the particular version of sed isn't performing as it should (due to different sed counterpart).

My ifconfig -a output (I only want to see the netmask):

    xennet0: flags=8863<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST> mtu 1500
            capabilities=2800<TCP4CSUM_Tx,UDP4CSUM_Tx>
            enabled=0
            address: 0a:3d:c0:98:c6:73
            inet 172.31.11.166 netmask 0xfffff000 broadcast 172.31.15.255
            inet6 fe80::83d:c0ff:fe98:c673%xennet0 prefixlen 64 scopeid 0x1
    lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33184
            inet 127.0.0.1 netmask 0xff000000
            inet6 ::1 prefixlen 128
            inet6 fe80::1%lo0 prefixlen 64 scopeid 0x2

Needed output (transformed output):

 0xfffff000
 0xff000000

My failed attempt:

ifconfig -a | egrep "0xf." | sed 's/inet //' | sed 's/netmask //' |
sed 's/ broadcast//' | sed 's/([0-9]{1,3}\.){3}[0-9]{1,3}//g' | sed 's/\s+//'

It gave me output as:

        172.31.11.166 0xfffff000 172.31.15.255
        127.0.0.1 0xff000000

I expected it to give my needed output.

Help will be of great assistance. I am using NetBSD 6.1.5 (Amazon EC2), however, I believe any general fixture should work.


Solution

  • Use Grep with Extended Regular Expressions

    You can use grep's ERE engine and the --only-matching flag to extract just the hex values. To do this, use egrep or grep -E to turn on extended regular expressions. For example:

    $ egrep -o '0x[[:xdigit:]]{8}' /tmp/corpus 
    0xfffff000
    0xff000000
    

    Likewise, you can also pipe in output and get the same results with:

    $ ifconfig -a | egrep -o '0x[[:xdigit:]]{8}'
    

    This works with both GNU and BSD greps, and doesn't rely on the PCRE library. It should therefore work on most modern systems without the need to tweak anything.