How can I prevent additional newlines with set-content while keeping existing ones when saving in UTF8?

前端 未结 2 983
北恋
北恋 2021-01-13 20:26

I have a small powershell script which reads a document with UTF8 encoding, makes some replacements in it and saves it back which looks like this:

(Get-Conte         


        
2条回答
  •  借酒劲吻你
    2021-01-13 21:00

    [IO.File]::WriteAllText() assumes that $content is a single string, but Get-Content produces an array of strings (and removes the line breaks from the end of each line/string). Mangling that string array into a single string joins the strings using the $OFS character (see here).

    To avoid this behavior you need to ensure that $content already is a single string when it's passed to WriteAllText(). There are various ways to do that, for instance:

    • Use Get-Content -Raw (PowerShell v3 or newer):

      $content = (Get-Content $path -Raw) -replace 'myregex', 'replacement'
      
    • Pipe the output through Out-String:

      $content = (Get-Content $path | Out-String) -replace 'myregex', 'replacement' -replace '\r\n$'
      

      Note, however, that Out-String (just like Set-Content) adds a trailing line break, as was pointed out in the comments. You need to remove that with a second replacement operation.

    • Join the array with the -join operator:

      $content = (Get-Content $path) -replace 'myregex', 'replacement' -join "`r`n"
      

提交回复
热议问题