gpt4 book ai didi

powershell - 以 UTF8 保存时,如何在保留现有换行符的同时防止使用 set-content 额外换行符?

转载 作者:行者123 更新时间:2023-12-03 09:54:10 29 4
gpt4 key购买 nike

我有一个小的 powershell 脚本,它读取使用 UTF8 编码的文档,在其中进行一些替换并将其保存回来,如下所示:

(Get-Content $path) -Replace "myregex","replacement" | Set-Content $path2 -Encoding utf8

这将创建一个具有正确编码和正确内容的新文件,但末尾有额外的换行符。根据 this answer 和许多其他人的说法,我被告知:
  • -NoNewLine
  • 中加入参数 Set-Content
  • 使用 [System.IO.File]::WriteAllText($path2,$content,[System.Text.Encoding]::UTF8)

  • 两种解决方案都会删除尾随的新行... 和文件 中的所有其他新行。

    有没有办法做到:
  • 保存文件时删除尾随的新行。
  • 在我的文件中保留现有的新行。
  • 最佳答案

    [IO.File]::WriteAllText() 假设 $content 是单个字符串,但 Get-Content 生成一个字符串数组(并从每行/字符串的末尾删除换行符)。将该字符串数组重组为单个字符串会使用 $OFS 字符连接字符串(请参阅 here )。

    为了避免这种行为,您需要确保 $content 在传递给 WriteAllText() 时已经是单个字符串。有多种方法可以做到这一点,例如:

  • 使用 Get-Content -Raw(PowerShell v3 或更新版本):
    $content = (Get-Content $path -Raw) -replace 'myregex', 'replacement'
  • 通过 Out-String 管道输出:
    $content = (Get-Content $path | Out-String) -replace 'myregex', 'replacement' -replace '\r\n$'

    但是请注意,正如评论中指出的那样, Out-String (就像 Set-Content )添加了一个尾随换行符。您需要通过第二次替换操作将其删除。
  • 使用 -join 运算符加入数组:
    $content = (Get-Content $path) -replace 'myregex', 'replacement' -join "`r`n"
  • 关于powershell - 以 UTF8 保存时,如何在保留现有换行符的同时防止使用 set-content 额外换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43742108/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com