Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to replace only certain characters of a string using powershell

I am writing a powershell script that uses the ip address to generate the network address (10.12.142.12 to 10.12.142.0) All of the ip addresses that I will be handling follow the following format 10.xxx.xxx.12

I have tried using the String.Replace() method. It works until the ip address is something like the following 10.12.154.12 or 10.214.126.12. It grabs and replaces all the .12. Ive also tried some regex, but couldn't come up with an expression that matches only the last octet.

$ipAddress = "10.12.23.12"
$networkNumber = $ipAddress.replace(".12",".0")

I want 10.12.23.0, but I get 10.0.23.0

like image 675
streetking93 Avatar asked Jan 01 '23 19:01

streetking93


1 Answers

Either remove everything from the last . with String.Remove() and String.LastIndexOf(), then add .0:

$ipAddress = "10.12.23.12"
$network = $ipAddress.Remove($ipAddress.LastIndexOf('.')) + '.0'

or use a regular expression that only replace .12 at the end of the string:

$ipAddress = "10.12.23.12"
$network = $ipAddress -replace '\.\d{1,3}$','.0'

Both of these will work with any value in the last octet, not just .12

like image 147
Mathias R. Jessen Avatar answered Jan 03 '23 08:01

Mathias R. Jessen