我有一个小的powershell脚本,该脚本读取UTF8编码的文档,在其中进行一些替换,然后将其保存起来,如下所示:
(Get-Content $path) -Replace "myregex","replacement" | Set-Content $path2 -Encoding utf8
Run Code Online (Sandbox Code Playgroud)
这将创建一个具有正确编码和正确内容的新文件,但末尾还有其他换行符。根据这个答案和许多其他答案,我被告知要:
-NoNewLine到Set-Content[System.IO.File]::WriteAllText($path2,$content,[System.Text.Encoding]::UTF8)两种解决方案都删除尾随的新行... 以及文件中的所有其他新行。
有两种方法都可以:
使用Set-Content -NoNewline(PSv5+) 是一种选择,但前提是您将输出作为带有嵌入换行符的单个字符串传递,这样Get-Content -Raw可以:
(Get-Content -Raw $path) -replace 'myregex', 'replacement' |
Set-Content -NoNewline $path2 -Encoding utf8
Run Code Online (Sandbox Code Playgroud)
但是请注意,该语义-replace与使用的变化-Raw:现在一个单一
-replace操作是在一个执行多行的字符串(整个文件的内容) -而不是线个别操作与阵列作为LHS。
另请注意,这-Raw将保留输入的尾随换行或非状态。
如果您想要逐行语义和/或想要确保输出的最后一行没有尾随换行符(即使输入文件有换行符),请使用Get-Contentwithout -Raw,然后使用-join:
(Get-Content $path) -replace 'myregex', 'replacement' -join [Environment]::NewLine |
Set-Content -NoNewline $path2 -Encoding utf8
Run Code Online (Sandbox Code Playgroud)
以上在输出中使用适合平台的换行符,但请注意,不能保证输入文件使用相同的换行符。
至于你尝试了什么:
正如您所观察到的,Set-Content -NoNewline使用字符串数组会导致所有字符串在没有分隔符的情况下连接- 与人们可能期望的不同,-NoNewline它不仅省略了尾随换行符:
> 'one', 'two' | Set-Content -NoNewline t.txt; Get-Content -Raw t.txt
onetwo # Strings were directly concatenated.
Run Code Online (Sandbox Code Playgroud)
注意:然而,嵌入在输入字符串中的换行符会被保留。
[IO.File]::WriteAllText()正如 Ansgar 的回答中所解释的那样,这种方法不会产生任何换行符的原因是不同的。
[IO.File]::WriteAllText()假定这$content是一个字符串,但Get-Content产生一个字符串数组(并从每个行/字符串的末尾删除换行符)。将字符串数组改成单个字符串会使用$OFS字符将字符串连接起来(请参阅此处)。
为避免这种行为,您需要确保$content在传递给时已经是一个字符串WriteAllText()。有多种方法可以做到这一点,例如:
使用Get-Content -Raw(PowerShell v3或更高版本):
$content = (Get-Content $path -Raw) -replace 'myregex', 'replacement'
Run Code Online (Sandbox Code Playgroud)通过Out-String以下管道输出:
$content = (Get-Content $path | Out-String) -replace 'myregex', 'replacement' -replace '\r\n$'
Run Code Online (Sandbox Code Playgroud)
但是请注意,正如注释中指出的那样,Out-String(就像一样Set-Content)会添加尾随换行符。您需要通过第二次替换操作将其删除。
用-join运算符加入数组:
$content = (Get-Content $path) -replace 'myregex', 'replacement' -join "`r`n"
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |