0

This question already has an answer here:

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.

marked as duplicate by Wildcard, techraf, mdpc, don_crissti, Jeff Schaller Dec 9 '16 at 1:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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 9 '16 at 1:20
  • It was not clear from the beginning. I updated my answer. – George Vasiliou Dec 9 '16 at 1:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.