≡ Menu

Powershell : Replace new line and tabs in a string with nothing or comma

While dealing with some dotnet exception, I faced a weird problem. The exception returned by dotnet exception is having newline characters in it and it is causing my output to clutter. So, the technique I used to get rid of the situation is, replace the new line characters with space or comma.

Replace new line characters with comma.

To get rid of newline characters from from the above string, you can replace them with space.

$myvar.replace("`n"," ")

Similarly to replace newline with comma, replace space with comma character. Like this you can replace with any other character you want.


Well, hold on. I believe you know know that different Operating Systems treats newline character different. While MAC OS treats \r (Carriage return) as newline our favorite windows treats “\r\t” as newline. So it is always wise to replace both \r and \n from the raw string to get rid of the newlines.


Similarly if you want to replace the tabs, use the same trick


Hope this helps…

{ 4 comments… add one }
  • Raghav January 14, 2018, 6:40 pm

    After searching stackoverflow for a good solution to replacing newlines and facing issues because I was not replacing the carriage return, this site helped. Thanks a lot!

  • Roman K March 19, 2019, 2:21 am

    Thank you so much. It helped me replace 2 million line breaks!

  • Ken M June 2, 2020, 3:25 am

    None of these methods have worked to remove unwanted paragraph markers. Please Help!
    (Get-Content c:\Test\CRLF\SampleText.txt).replace(‘`\r`\n’, ”) | Set-Content c:\Test\CleanSampleText.txt

    (Get-Content c:\Test\CRLF\SampleText.txt).replace(‘[char]10’, ”) | Set-Content c:\Test\CleanSampleText.txt

    (Get-Content c:\Test\CRLF\SampleText.txt).replace([char]13, ”) | Set-Content c:\Test\CleanSampleText.txt

    (Get-Content c:\Test\CRLF\SampleText.txt).replace(‘`n’, ”) | Set-Content c:\Test\CleanSampleText.txt

    (Get-Content c:\Test\CRLF\SampleText.txt).replace(“`n”,””) | Set-Content c:\Test\CleanSampleText.txt

Leave a Comment