Take the 2-minute tour ×

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.

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

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($_)}

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.

share|improve this answer
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 Apr 19 '12 at 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 Apr 19 '12 at 19:21
add comment

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)
share|improve this answer
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 Apr 4 '12 at 7:35
add comment

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.

share|improve this answer
add comment

Your Answer


