How to control the line separator in a powershell pipeline?

powershell

Solution

You could use StreamWriter instead of the Out-File cmdlet like this:

$writer = [system.io.file]::CreateText("\path\to\db.cfg.new")
$writer.NewLine = "`n"
get-content db.cfg | %{$_ -replace 'a', 'b'} | % { $writer.WriteLine($_)}
$writer.Close()

It's not quite as slick as a one-liner, but at least it's easy to read and you're still streaming the file one line at a time.

Problem

Assume the simple file substitution below: ``` get-content db.cfg | %{$_ -replace 'a', 'b'} | out-file db.cfg.new -encoding default ``` out-file automatically uses \r\n as a line separator. Is there a way to force a different separator (like \n)? I'm looking for an elegant solution. Other than that, one can certainly build the whole file as a string in memory and then write it out.

Original source