I have a script in which I need to parse the IP address of the localhost, and replace the 2nd octet with a different value, but the value being substituted depends on what the value currently is...
For example, if the IP is 10.10.100.6, then I need the result to be 10.20.100.6, and if the IP is 10.20.100.6, then I need the result to be 10.10.100.6
I tried the following:
nmcli con show eno16777984 | grep -E '^ipv4.address' | awk -F"/|[[:space:]]+" '{print $2}' | sed -e 's/^10\.10\./10.20./; s/^10\.20\./10\.10\./'
And the problem I'm having with that, is that the sed
substitutions happen in order they are set in the command. So the result is always 10.10....
Is there a way to have sed replace values only if the current value matches a pattern?
Thanks!
P.S. This needs to be a short and simple one liner, as this line of code will be executed via substitution in a few places, and whoever does it will have limited experience/knowledge, so will just be copying and pasting from a document.
Update
I ended up finding out how to do this via awk
:
nmcli con show eno16777984 | grep -E '^ipv4.address' | awk -F"/|[[:space:]]+" '{print $2}' | awk -F. '{print $1"."($2 == "10" ? "20" : "10")"."$3"."$4}'
But there are some good and simple answers showing how to do it in sed
below.
nmcli
,grep
andawk
by a singlehostname -i
. Or maybe it'll return the IPv6, but if you haven't tried yet it's worth a shot.