PowerShell: How to Remove All Newlines from String


You can use the following syntax to remove all newline characters from a string in PowerShell:

$my_string = [string]::join("",($my_string.Split("`n")))

This particular example removes all newline characters from the string stored in the variable named $my_string.

Note: We use a backtick when referencing a newline ( `n ) and not a single quote. This is a common mistake to avoid. 

The following example shows how to use this syntax in practice.

Example: How to Remove All Newlines from String in PowerShell

Suppose that we create the following string in PowerShell that contains two newline characters:

$my_string = "Hey there`nMy name is Zach`nGreat to meet you."

When we view this string in PowerShell, it will be displayed on three separate lines:

Suppose that we would like to remove all of the newline characters from the string.

We can use the following syntax to do so:

$new_string = [string]::join("",($my_string.Split("`n")))

The following screenshot shows how to use this syntax in practice:

PowerShell remove newlines from string

Notice that all newline characters have been removed from the string.

The new string is now:

  • Hey thereMy name is ZachGreat to meet you.

If you would instead like to replace each newline character with a space, then you can use the following syntax:

$new_string = [string]::join(" ",($my_string.Split("`n")))

The following screenshot shows how to use this syntax in practice:

PowerShell replace newlines with space in string

Notice that all newline characters in the string have been replaced with a single space.

The new string is now:

  • Hey there My name is Zach Great to meet you.

Feel free to use the join method in PowerShell to replace each newline character in a string with any other character that you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Count Specific Characters in String
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply