Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing new line with space with powershell

Hi so I've been looking into this for a while and nothing I've tried has worked. Forgive me for asking this again, but I cannot replace a new line with a space in powershell

$path = "$root\$filename"
Get-Content $path | % $_.Replace "`r`n"," " | Set-Content "$root\bob.txt" -Force

This is one of the many things I've tried just looking around on this site.

I'm using powershell v3

like image 664
Patrick Mahoney Avatar asked Dec 05 '22 18:12

Patrick Mahoney


2 Answers

Keith Hill's helpful answer explains the problem with your code well and provides a working solution.

However, Keith's solution adds a trailing space to the output line (as your own solution attempt would have done, had it worked).

Here's a simpler alternative that avoids this problem.

(Get-Content $path) -join ' ' | Set-Content -Force $root\bob.txt
  • (Get-Content $path) returns an array of lines,
  • which we then join to form a single output string, with elements separated by a space each - this logic only places the separator (a space) between elements, and not also at the end.

Note that both this and Keith's answer require reading the entire input file into memory, which is potentially problematic with large files.

like image 58
mklement0 Avatar answered Dec 12 '22 02:12

mklement0


A couple of issues here. First, the way you are calling Get-Content, the strings sent down the pipe will never have a newline in them. That's because the default way Get-Content works is to split the file up on newline and output a string for each line. Second, your Foreach command requires {} around the replace command. Try this:

Get-Content $path -Raw | Foreach {$_ -replace "`r`n",' '} | 
    Set-Content $root\bob.txt -Force

The -Raw parameter instructs Get-Content to read the file contents in as a single string. This will preserve the CRLFs.

like image 40
Keith Hill Avatar answered Dec 12 '22 03:12

Keith Hill