Techibee.com

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.

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

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.

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

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

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

Hope this helps…

Exit mobile version