Chand
Chand

Reputation: 320

Using Match pattern in powershell to replace data

$Gateway = "192.168.122.1"
$Ip = "172.18.66.34"

My goal is to get the output as below.

172.18.66.1

1st 3 octet of $IP and 4th octet of $Gateway....combination of both...

I tried below but its not working any other logic to achieve this

$Gateway -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.(?<content>)"
$fourth = $matches['content']
$mgmt = "172.18.47.19"
$mgmt -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.(?<content>.*)"
$new = $matches['content']
$mgmt.replace($new,$fourth)

Upvotes: 0

Views: 65

Answers (3)

Matt
Matt

Reputation: 46710

I know it's not regex but this is a super reason to introduce you to the type [ipaddress]

$Gateway = "192.168.122.1"
$Ip = "172.18.66.34"

(([ipaddress]$Ip).GetAddressBytes()[0..2] + ([ipaddress]$Gateway).GetAddressBytes()[-1]) -join "."

We use the method .GetAddressBytes() to break out the octets and then just use array notation, concatenation and a simple -join to reform the address to your standard.

Upvotes: 1

Avshalom
Avshalom

Reputation: 8889

Maybe Primitive, but does the job

($Ip -split "\.")[0],($Ip -split "\.")[1],($Ip -split "\.")[2],($Gateway -split "\.")[-1] -join "."

172.18.66.1

works on powershell 2

is that what you mean?

Upvotes: 1

Frode F.
Frode F.

Reputation: 54871

You forgot to fill in a pattern in the "content"-caturing group.

Try this:

$Gateway -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.(?<content>\d{1,3})"

Upvotes: 1

Related Questions