使用powershell替换txt文件中的文本块
replace block of text inside txt file using powershell
我有以下 powershell 脚本,它可以替换任何文本文件中的多行文本,并且效果很好,但我对它有一点不满。每当它替换我想要的行时,它都会在 txt 文件的末尾添加一个空行。
代码:
$oldCode = @"
<uservalue1 value="0" />
<uservalue1 value="1" />
"@
$newCode = @"
<uservalue1 value="1" />
<uservalue1 value="2" />
"@
ls myfile.txt | foreach {
$fileContent = Get-Content $_.FullName -Raw
$newFileContent = $fileContent -replace $oldCode, $newCode
Set-Content -Path $_.FullName -Value $newFileContent
}
这只会更改两个值,但它还会添加一个额外的换行符,因此当此脚本一天运行多次时,我们最终会得到一个末尾包含空行的大文件。
有什么办法可以避免这种情况吗?
使用-NoNewline
参数
Set-Content -NoNewline -Path $_.FullName -Value $newFileContent
我有以下 powershell 脚本,它可以替换任何文本文件中的多行文本,并且效果很好,但我对它有一点不满。每当它替换我想要的行时,它都会在 txt 文件的末尾添加一个空行。
代码:
$oldCode = @"
<uservalue1 value="0" />
<uservalue1 value="1" />
"@
$newCode = @"
<uservalue1 value="1" />
<uservalue1 value="2" />
"@
ls myfile.txt | foreach {
$fileContent = Get-Content $_.FullName -Raw
$newFileContent = $fileContent -replace $oldCode, $newCode
Set-Content -Path $_.FullName -Value $newFileContent
}
这只会更改两个值,但它还会添加一个额外的换行符,因此当此脚本一天运行多次时,我们最终会得到一个末尾包含空行的大文件。
有什么办法可以避免这种情况吗?
使用-NoNewline
参数
Set-Content -NoNewline -Path $_.FullName -Value $newFileContent