0

Assume having the following file

Somestring 1.2.3.4 more charachters and strings
Somestring 1.2.3.5 more charachters and strings
Somestring 1.2.3.6 more charachters and strings

I want to change the last octet in IP:

Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

How can I achieve this in awk or sed?

What I did is:

awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH-1); print ip }' file  

but this only prints the ip and is not entirely correct.

Furthermore I tried:

awk '{split($2,ip,".") gsub(ip[2],"x"); print}' 

but this is also not correct since It replacing first octet as well.

Somestring x.2.3.x more charachters and strings
Somestring x.2.3.x more charachters and strings
Somestring x.2.3.x more charachters and strings

Thanks for help

1

Using sed for this:

$ sed -E 's/ (([0-9]{1,3}\.){3})[0-9]{1,3} / \1x /' file
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

This looks for a space followed by three sets of [0-9]{1,3}\. (a one to three digit number followed by a dot), which is captured into \1. Then we also replace a last set of [0-9]{1,3} and a final space. This is all replaced by ␣\1x␣ where \1 is the first group of three numbers and dots.

  • Works nicely thanks! Can you also provides version with awk? – holasz Apr 25 '18 at 13:41
  • @holasz Is the initial Somestring a single word? And why do you need multiple ways of doing the same thing? – Kusalananda Apr 25 '18 at 13:45
  • @Kusalanada I was just curious but got the awk verion from steeldriver. Thank you both. Since you were first, I considering your answer correct. Thanks . – holasz Apr 25 '18 at 13:50
1

If you really want to do this in awk, then you need to anchor the expression - and you only need sub not gsub since it's a single replacement e.g.

awk '{sub(/\.[0-9][0-9]?[0-9]?$/,".x",$2)} 1' input
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

With some implementations you can use ERE [0-9]{1,3} for the digit repeat.

1
awk '{sub(/.$/,"x",$2)}1' file

Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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