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
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,Note that both this and Keith's answer require reading the entire input file into memory, which is potentially problematic with large files.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With