PowerShell: How to Replace Comma with Newline


Often you may want to use PowerShell to replace all commas with newlines in a particular file.

You can use the following syntax to do so:

(Get-Content team_names.txt) -replace ",","`n" | Set-Content team_names2.txt

This particular example replaces all commas with newlines in the file named team_names.txt and saves the results to a new file named team_names2.txt.

Note: You must use double quotes in this scenario when using the -replace operator.

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

Example: How to Replace Commas with Newlines in PowerShell

Suppose we have a file in our current directory named team_names.txt that contains the names of various basketball teams.

We can use the Get-Content cmdlet to view the contents of this file:

We can see that the file contains the names of various basketball teams separated by commas.

We can use the following syntax to replace each comma in the file with a newline instead:

(Get-Content team_names.txt) -replace ",","`n" | Set-Content team_names2.txt

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

PowerShell replace comma with newline

Notice that when we use the Get-Content cmdlet to view the contents of the new team_names2.txt file we can see that all commas have been replaced with newlines.

Each of the team names is now shown on its own line.

Note: You can find the complete documentation for the -replace operator in PowerShell here.

Related Tutorials

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

PowerShell: How to Replace Text in String
PowerShell: How to Get String Length of Variable
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply