2

Lets say I have a string that can be any possible/valid network address like so:

STR="192.168.1.0/24"

What I want to do is replace the last octet (in this case it's 0/24, however it can be anyting) with the number 2, however I don't know what the last octet could (do not will be print the new value, so change:

192.168.1.0/24

to:

192.168.1.2

Whatever the network address is, I want to replace the last octet with "2"

Note: it is not important to check if the string is a valid network address as all strings being tested are assumed to be valid network addresses.

tim
  • 105

1 Answers1

6

In terminal this worked:

echo "192.168.1.0/24" | sed  -n 's/0.24/2/p' 

In script this works:

str="192.168.1.0/24"
newstr=$(sed  -n 's/0.24/2/p' <<<$str)

To replace last digit of any IP address:

str="192.111.12.20"
newstr=$(awk -F"." '{print $1"."$2"."$3".2"}'<<<$str)
echo $newstr
  • thanks for the reply but 192.168.1.0/24 was just an example and the string can be any possible network address. Whatever the network address is, I want to replace the last octet with "2" – tim Dec 09 '16 at 01:20
  • It was not clear from the beginning. I updated my answer. – George Vasiliou Dec 09 '16 at 01:37
  • How to reduce last 4 digits by 2 , newstr=$(awk -F"." '{print $1"."$2"."$3"."$4"-2"}'<<<$str). This is returning as string 4-2 – Daniel Apr 19 '20 at 16:27
  • 2
    Trying to turn myip = 192.168.0.1 into 192.168.0.1/24. This helped! $(awk -F"." '{print $1"."$2"."$3".1//24"}'<<<$myip) – Twisty Sep 04 '20 at 21:45