1

I have a string wit a following content, delimited by semicolons:

echo $content

BCS3;BCS2;DigitalIO;GAElectricDrive;J1939;SKF15;UBloxGNSS;VIMS

Perhaps my question is noob, but I cannot figure out, how to sort this values alphabetically, e.g. I want to receive following output(first and second elements are not in alphabetical order):

BCS2;BCS3;DigitalIO;GAElectricDrive;J1939;SKF15;UBloxGNSS;VIMS
Vasyl Stepulo
  • 1,493
  • 1
  • 23
  • 43

1 Answers1

2
$Content = "BCS3;BCS2;DigitalIO;GAElectricDrive;J1939;SKF15;UBloxGNSS;VIMS"

$Content = ($Content -split ';'|Sort) -Join ';'

$content
BCS2;BCS3;DigitalIO;GAElectricDrive;J1939;SKF15;UBloxGNSS;VIMS

But the sorting is alphabetical, words containing numbers with differing places are sorted 1,10,100,2,20,200.

To avoid this you can use $ToNatural

$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
$Content = "1;10;100;2;20;200"
$Content = ($Content -split ';'|Sort $ToNatural) -Join ';'
$content
1;2;10;20;100;200
  • lol - that's great. I got my inspiration from [this](https://gist.github.com/markwragg/e2a9dc05f3464103d6998298fb575d4e). Perhaps you did to? – Lieven Keersmaekers Jun 15 '18 at 12:11
  • 1
    I think the link `HE` refers to is from [Ronan Kuzmin](https://stackoverflow.com/a/5429048/6811411) and the/one origin. I have `$ToNatural` in my profile. –  Jun 15 '18 at 12:15
  • @LotPings Thanks! I only need alphabetical, but your answer more than enough! – Vasyl Stepulo Jun 15 '18 at 12:37