使用 powershell 3 替换文件中的一行文本
Replace a line of text in a file using powershell 3
我正在尝试替换文件中的一些文本。目前我将 IP 地址替换为:
(Get-Content $editfile) | ForEach-Object { $_ -replace "10.10.37.*<", "10.10.37.$BusNet<" } | Set-Content $editfile
此代码在这里运行良好。但是我无法让代码与另一行一起工作:
<dbserver>SVRNAME</dbserver>
这是我为这一行编写的代码:
(Get-Content $editfile) | ForEach-Object { $_ -replace "<dbserver>*</dbserver>", "$DbSVRName" } | Set-Content $editfile
上面的代码应该用 DbSVRName 替换 SVRNAME。然而事实并非如此。我知道这很简单,而且我知道之后我会感到很愚蠢。我错过了什么?
在调试试图找到解决方案时,我发现由于某种原因它看不到 *
(Get-Content $editfile) | ForEach-Object { $_ -match "<dbserver>*</dbserver>" }
这段代码揭示了所有错误的结果。
*
不捕获正则表达式中的内容,您需要 .*
,特别是 (.*?)
$str = 'text <dbserver>SVRNAME</dbserver> text'
$replace = 'foo'
$str -replace '(<dbserver>)(.*?)(</dbserver>)', (''+$replace+'')
输出
text <dbserver>foo</dbserver> text
我正在尝试替换文件中的一些文本。目前我将 IP 地址替换为:
(Get-Content $editfile) | ForEach-Object { $_ -replace "10.10.37.*<", "10.10.37.$BusNet<" } | Set-Content $editfile
此代码在这里运行良好。但是我无法让代码与另一行一起工作:
<dbserver>SVRNAME</dbserver>
这是我为这一行编写的代码:
(Get-Content $editfile) | ForEach-Object { $_ -replace "<dbserver>*</dbserver>", "$DbSVRName" } | Set-Content $editfile
上面的代码应该用 DbSVRName 替换 SVRNAME。然而事实并非如此。我知道这很简单,而且我知道之后我会感到很愚蠢。我错过了什么?
在调试试图找到解决方案时,我发现由于某种原因它看不到 *
(Get-Content $editfile) | ForEach-Object { $_ -match "<dbserver>*</dbserver>" }
这段代码揭示了所有错误的结果。
*
不捕获正则表达式中的内容,您需要 .*
,特别是 (.*?)
$str = 'text <dbserver>SVRNAME</dbserver> text'
$replace = 'foo'
$str -replace '(<dbserver>)(.*?)(</dbserver>)', (''+$replace+'')
输出
text <dbserver>foo</dbserver> text