mansing shinde
mansing shinde

Reputation: 465

Trying to replace string using Powershell regex

My text file is as below

( HOST = <something numeric> )

Want to replace HOST value. So trying with below regx but no go

(Get-Content C:\Go\test.txt).replace("\HOST\s*=\s*.+\s*\", " HOST = 8888 ") | Set-Content C:\Go\test.txt

Any help?

Upvotes: 1

Views: 6874

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to make sure you use a regex replacement with the following regex:

PS> $s = "( HOST = 111111 )"
PS> $s -replace "HOST\s*=\s*\d+\s*", " HOST = 8888 "
(  HOST = 8888 )

Here, HOST\s*=\s*\d+\s* matches:

  • HOST - a literal HOST string
  • \s*=\s* - a = enclosed with 0+ whitespaces
  • \d+ - 1 or more digits
  • \s* - 0+ whitespaces.

If the *.ora file is UTF8 encoding without BOM, you need to use

$MyPath = 'C:\Go\test.txt'
$MyFile = Get-Content $MyPath
$MyFile = $MyFile -replace "HOST\s*=\s*\d+\s*", " HOST = 8888 "
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines($MyPath, $MyFile, $Utf8NoBomEncoding)

Upvotes: 2

Related Questions