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

PowerShellMicrosoft TechnologiesSoftware & Coding

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 (' ',',')
raja
Updated on 20-Nov-2020 08:50:44

Advertisements