Search code examples
linuxbashpipeoutputcut

cut ip addresses from config file


I have the following output:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=00:00:00:00:00:00, bridge=eth1' ]

Sometimes, there is only one ip address. So it's:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1' ]

And in other cases, there are more than 2 ip addresses:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=11:11:11:11:11:11, bridge=eth1', 'ip=9.1.2.3, mac=22:22:22:22:22:22, bridge=eth1' ]

Is there an easy way to get only the ip addresses? I want to store them in an array.


Solution

  • This is one possibility out of many: tr -s "[,'" "\n" | grep "^ip=" | cut -d "=" -f2

    Example:

    echo "vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=11:11:11:11:11:11, bridge=eth1', 'ip=9.1.2.3, mac=22:22:22:22:22:22, bridge=eth1' ]" | tr -s "[,'" "\n" | grep "^ip=" | cut -d "=" -f2
    

    produces

    1.2.3.4
    5.6.7.8
    9.1.2.3