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

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


Replacing new line with space with powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply