Replacing Duplicate Spaces

by Sep 26, 2014

All PowerShell Versions

To eliminate any duplicate space, try this regular expression:

PS> '[  Man, it    works!   ]' -replace '\s{2,}', ' '
[ Man, it works! ] 

You can use this approach also to convert fixed-width text tables to CSV data:

PS> (qprocess) -replace '\s{2,}', ','
>tobias,console,1,3876,taskhostex.exe
>tobias,console,1,3844,explorer.exe
>tobias,console,1,4292,tabtip.exe

Once it is CSV, you can use ConvertFrom-Csv to turn text data into objects:

 
PS> (qprocess) -replace '\s{2,}', ',' | ConvertFrom-Csv -Header Name, Session, ID, Pid, Process


Name    : >tobias
Session : console
ID      : 1
Pid     : 3876
Process : taskhostex.exe

Name    : >tobias
Session : console
ID      : 1
Pid     : 3844
Process : explorer.exe

Name    : >tobias
Session : console
ID      : 1
Pid     : 4292
Process : tabtip.exe 
(...)

Twitter This Tip! ReTweet this Tip!