How to convert raw text to the CSV (Comma Separated Values) in PowerShell?


We have a raw text example and to convert it into the CSV values, we can use below code.

Example

PS C:\> $text = "This is a PowerShell latest version" PS C:\> $text.Replace(' ',',')

Output

This,is,a,PowerShell,latest,version

If there are multiple spaces between the keywords then the above replace command would go wrong. For example,

Example

PS C:\> $text = "This is a PowerShell latest version" PS C:\> $text.Replace(' ',',')

Output

This,,is,,,a,,,,PowerShell,latest,version

So we can use another method as shown below.

$text -replace '\s+',' '

In the above command, \S indicates the whitespace and + indicates the occurrence of the specific character. So more than one white space will be removed.

Next is to add the comma (,) between them so the whole command will be as below.

($text -replace '\s+',' ') -replace (' ',',')

Updated on: 20-Nov-2020

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements