Removing more than one white space in powershell

2020-02-27 05:27发布

问题:

I was trying to find a way in powershell to remove more than one white space.

But what i found is how to do it in php. "Removing more than one white-space"

There will be similar regular expression may available .

How to acheive the same in powershell?

My string is like this

Xcopy Source  Desination

Some lines may contain more than one white space between Source and destination.

回答1:

If you're looking to collapse multiple consecutive whitespace characters into a single space then you can do this using the -replace operator:

'[     Hello,     World!     ]' -replace '\s+', ' '

...returns...

[ Hello, World! ]

The first parameter to -replace is a regular expression pattern to match, and the second parameter is the text that will replace any matches. \s will match a whitespace character, and + indicates to match one or more occurrences, so, in other words, one or more adjacent whitespace characters will be replaced with a single space. Enter help about_comparison_operators or see here for more information.