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.
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.
What about a post creation convertion ?
$fileToConvert = "db.cfg.new"
$filName = "db.cfg"
$text = ([IO.File]::ReadAllText($fileToConvert) -replace "`r`n?", "`n")
$encoding = New-Object System.Text.ASCIIEncoding
[IO.File]::WriteAllText("$filename", $text, $encoding)
It looks like it's not possible to control the line separator when using out-file at the end of a pipeline.
But of course, you can build the file as a string in memory or convert the line endings after saving the file.
I solved my use case by using Swiss File Knife instead of PowerShell to perform the substitution. It just didn't feel right implementing a workaround for such a basic problem.