1

How to using sed to change the last character from a match line ?

Exemple: /etc/network/interfaces

auto eth0
iface eth0 inet static
        address 150.0.3.50
        netmask 255.255.255.0
        network 150.0.3.0
        gateway 150.0.3.6


auto eth.....

How can I change only the host octet of the gateway ? I've a lot of machines to do that and each one is in a different network, but the gateway's octet is always the same.

rodolpho
  • 23
  • 4
  • Can you be more specific providing both an example from and example to? Most likely, your answer is going to be something like `sed -e 's@\(gateway [0-9.]+\)\.[0-9]+@\1.6@i'` but it's hard to know for sure. – Andrew Domaszek Mar 08 '15 at 03:17

1 Answers1

1

If your gateway is 150.0.3.254 You can do it this way:

sed -i -E 's/([ \t]+gateway[ \t])+[0-9.]+/\1150.0.3.254/' /etc/network/interfaces

Let me explain how it works:

  • -i -> Means replace the file
  • -E -> Use Extended regular expressions, avoids escape especial characters like ( to \(
  • 's/<PATTERN>/<REPLACEMENT>/' -> thes` means substitution for the pattern to the replacemnet
  • [ \t]+ -> Space or Tab one or more occurrences.
  • [0-9.]+ -> Numbers from 0 to 9 and dot one or more occurrences (for the ip)
  • (PATTERN) \1 -> The pattern inside () is stored as group 1 \1, so it will be used on the replacement (in this case spaces or tabs + "gateway" + spaces or tabs)
  • 150.0.3.254 -> Is the desired gateway

Best regards

Dedalo
  • 56
  • 6