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.

0

1 Answer 1

5

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
4
  • 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" Commented Dec 9, 2016 at 1:20
  • It was not clear from the beginning. I updated my answer. Commented Dec 9, 2016 at 1: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 Commented Apr 19, 2020 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) Commented Sep 4, 2020 at 21:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.