在PowerShell脚本中,为了替换文件中第一次出现的字符串,我提供了下面的代码,该代码会在变量中跟踪是否进行了替换.
这样做有更优雅(惯用)的方式吗?
$original_file = 'pom.xml'
$destination_file = 'pom.xml.new'
$done = $false
(Get-Content $original_file) | Foreach-Object {
$done
if ($done) {
$_
} else {
$result = $_ -replace '<version>6.1.26.p1</version>', '<version>6.1.26.p1-SNAPSHOT</version>'
if ($result -ne $_) {
$done = $true
}
$result
}
} | Set-Content $destination_file
Run Code Online (Sandbox Code Playgroud)
所以,假设你有一个名为Test.txt的文件,它的内容是:
one
two
four
four
five
six
seven
eight
nine
ten
Run Code Online (Sandbox Code Playgroud)
并且您想要将四个的第一个实例更改为三个:
$re = [regex]'four'
$re.Replace([string]::Join("`n", (gc C:\Path\To\test.txt)), 'three', 1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5686 次 |
| 最近记录: |