How to manage line separator in powershell pipeline?

Let's assume a simple file substitution is below:

get-content db.cfg | %{$_ -replace 'a', 'b'} | out-file db.cfg.new -encoding default

      

out-file automatically uses \ r \ n as the line separator. Is there a way to force a different delimiter (like \ n)?

I am looking for an elegant solution. In addition, you can, of course, collect the entire file as a string in memory and then write it.

+3


source to share


3 answers


You can use StreamWriter instead of Out-File cmdlet, for example:

$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 as smooth as a one-liner, but at least it's easy to read and you're still transferring the file one line at a time.

+3


source


How about converting messages?



$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)

      

0


source


It looks like it is not possible to control the line separator when using an out file at the end of the pipeline.

But of course you can create the file as a string in memory, or convert the final strings after you save the file.

I decided to use it using Swiss File Knife instead of PowerShell to do the replacement. It just didn't feel right about applying a workaround for such a basic problem.

0


source







All Articles