jazza1000
jazza1000

Reputation: 4247

Bash script to replace characters at the end of a string

I am trying to write a bash script which will take an IP address number in the form 172.19.X.Y and replace it with 172.19.0.100.

Unfortunately, I am not that experienced with bash and sed and it is not quite working for me.

So far my closest effort is:

PrivateIp=$(sed -e 's/\([0-9]*\.[0-9]*\.\)*$/\10.100/' <<<"$PrivateIp")

which produces 172.19.X.Y0.100.

Upvotes: 0

Views: 595

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52536

You could use parameter substitution:

$ privateip='172.19.X.Y'
$ privateip=${privateip%.*.*}.0.100
$ echo "$privateip"
172.19.0.100

${privateip%.*.*} removes the shortest match of .*.* from the end of $privateip, which is .X.Y in this case.

Upvotes: 3

KamilCuk
KamilCuk

Reputation: 142045

The \1 is a reference to \(this\), you don't need if you just want to replace.

Just:

PrivateIp=$(sed -e 's/[0-9]*\.[0-9]*$/10.100/' <<<"$PrivateIp")

The [0-9]*\.[0-9]* will match <number><dot><number> The $ tells it to match from the end of the string.

Upvotes: 1

Related Questions