Question:
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
1 2 3 |
$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
Answer:
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.
1 2 |
(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.