How to control the line separator in a powershell pipeline?

Go To StackoverFlow.com

3

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.

2012-04-04 00:41
by Bogdan Calmac


3

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.

2012-04-18 18:26
by Eric Nicholson
I like this. And I could create my own out-file2 function which hides the details of this code and is as slick as the original one - Bogdan Calmac 2012-04-19 18:30
Absolutely! Keep in mind that the current PowerShell directory and the process' current directory won't necessarily be the same, so use full paths or set [Environment]::CurrentDirectory before opening the file - Eric Nicholson 2012-04-19 19:21


0

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)
2012-04-04 03:44
by JPBlanc
This would be even less elegant than working on a list of lines and then joining them using the delimiter of choice. I was hoping there is some undocumented $LINE_SEPARATOR that can be customized - Bogdan Calmac 2012-04-04 07:35


0

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.

2012-04-18 17:59
by Bogdan Calmac
Ads