2017-08-24 33 views
1

我的文本文件来替换字符串如下尝试使用PowerShell的regex

(HOST = <something numeric>) 

要替换HOST值。所以尝试以下雷克斯,但没有去

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

任何帮助吗?

+0

正则表达式应该是' “HOST \ s * = \ s * \ d + \ S *”'。但使用'-replace' –

+0

我必须使用get-content和set-content作为使用 - 替换文件格式并导致问题。基本上我试图替换tnsnames.ora文件的值,我可以使用'''cat“C:\ oraclexe \ app \ oracle \ product \ 11.2.0 \ server \ network \ ADMIN \ tnsnames.ora来实现。 %{$ _ -replace“\(HOST \ s * = \ s *。+ \ s * \)\(”,“(HOST = $ hostname_container)(”}>“C:\ tmp \ tnsnames.ora”' ' 该值正在被替换,但在连接过程中导致问题 –

+0

如果您的文件是二进制文件,那么我怀疑您可能使用正则表达式,它只对字符串内容进行操作 –

回答

0

你需要确保你使用正则表达式替换下面的正则表达式:

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

这里,HOST\s*=\s*\d+\s*比赛:

  • HOST - 文字HOST
  • \s*=\s* - 一个=附有0+空格
  • \d+ - 1或更多位数
  • \s* - 0+空格。

如果* .ORA文件是没有BOM UTF8编码,您需要使用

$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) 
+0

再次,我可以使用-replace - '''cat“C:\ oraclexe \ app \ oracle \ product \ 11.2.0 \ server \ network \ ADMIN \ tnsnames.ora“| %{$ _ -replace“\(HOST \ s * = \ s *。+ \ s * \)\(”,“(HOST = $ hostname_container)(”}>“C:\ tmp \ tnsnames.ora”' ''(我实际上将值替换为tnsnames.ora),但是这会导致连接问题。运行get-context | set-content时,值正在被替换并且连接正常工作。我只是试图用regx来管理替换 –

+0

@mansingshinde很高兴工作。如果答案对您有帮助和信息,请考虑upvoting。 –