【发布时间】:2019-01-10 22:11:43
【问题描述】:
我们想用特定的模式替换变量id=* 的多个实例,例如id=1234。
我已经制作了这个 Powershell 脚本(并且更喜欢继续使用 Powershell 作为解决方案):
$line = Get-Content C:\test.txt | Select-String "id=" | Select-Object -ExpandProperty Line
$content = Get-Content C:\test.txt
$content | ForEach {$_ -replace $line,"id=1234"} | Set-Content C:\test.txt
Get-Content C:\test.txt
只要只有 1 个 id=... 实例,此方法就有效,当文件包含 id=... 的多个实例时,根本不会执行替换步骤。
输入文件类似于:
text over here
id=1
text over here: id={123456}
text
id=number1
id=#3 text
id=3+3 text
这应该导致:
text over here
id=1234
text over here: id=1234
text
id=1234
id=1234 text
id=1234 text
【问题讨论】:
-
所以替换 id= 和后面的任何字符直到行尾?
(Get-Content C:\test.txt) | ForEach {$_ -replace "id=.*","id=1234"} -
带有positive lookbehind
(gc C:\test.txt) -replace '(?<=id=)[^\s]+','1234'的变体
标签: powershell replace find