3

I am manipulating a file with the Get-Content command, doing a replace then piping it to Set-Content or Out-File. But the the file gets written with a CR before all my linefeeds. My original file has linefeeds, which is OK, but the CR breaks the file for what its being used for.

I tried this Powershell replace content in file adds redundent carriage return

But cannot get it to work. And I would like to avoid using .NET if possible

Here is my code:

(Get-Content "FILE.TEMPLATE") -replace('SEQUENCE', "$NEWSEQUENCE") | Set-Content ("FILE.NEW")

or

(Get-Content "FILE.TEMPLATE") -replace('SEQUENCE', "$NEWSEQUENCE") | Set-Content ("FILE.NEW") -Encoding UTF8NoBOM

I tried setting the encoding with '-Encoding' after the Set-Content pipe, but that does nothing. Tried UTF8, UTF8NoBOM. This out put file is destined to be used to on a UNIX box, which is why the CR breaks the file.

Any ideas?

arealhobo
  • 411
  • 5
  • 13

1 Answers1

2

It took some more digging around and here is what worked

(Get-Content "FILE.TEMPLATE" -Raw) -replace 'SEQUENCE', "$NEWSEQUENCE" | 
  Set-Content "FILE.NEW" -NoNewLine -Encoding UTF8NoBOM

Had to add -Raw to Get-Content, then add -NoNewLine and -Encoding UTF8NoBOM to Set-Content.

This will only work with PowerShell 6+, since anything below does not have UTF8NoBOM as an encoding option. Powershell 5 defaults to UTF8BOM.

mklement0
  • 245,023
  • 45
  • 419
  • 492
arealhobo
  • 411
  • 5
  • 13
  • 1
    Nicely done; quibble: _Windows PowerShell_ (PowerShell up to version 5.1) _defaults_ to _ANSI_ encoding with `Set-Content`; however `-Encoding Utf8` _invariably_ means UTF-8 _with a BOM_ there, whereas _PowerShell [Core] 6+_ consistently _defaults_ to UTF-8 _without a BOM_ (which makes `-Encoding Utf8NoBom` unnecessary) - see [this answer](https://stackoverflow.com/a/40098904/45375). – mklement0 Mar 19 '20 at 02:25
  • 1
    Now I did read that PowerShell 6+ would default to UTF-8 without a BOM, but for some reason it was not working without it, reason I included. I will go back to make sure I tried it without the encoding option so I'm not misstating anything. Thank you. – arealhobo Mar 19 '20 at 03:04