szantaii
szantaii

Reputation: 165

PowerShell sort string array, where each element consists of two fields, by the second field

I have an array filled with strings like these (SHA256 checksums and relative paths delimited with a semicolon):

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855;./zzz.txt
d0c4c3e65c450251e44ec41c3c6ee0ea456d02bd74f041c9299934176ec325e6;./kkk.xlsx
9a1d469cdc7c2072b19a7e483a818c5e4e9de070298c60b34de29930e7b79209;./árvíztűrő tükörfúrógép/kkk - Shortcut.lnk

And I'd like to sort these rows by the second column. So the sorted array should look like this:

9a1d469cdc7c2072b19a7e483a818c5e4e9de070298c60b34de29930e7b79209;./árvíztűrő tükörfúrógép/kkk - Shortcut.lnk
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855;./zzz.txt
d0c4c3e65c450251e44ec41c3c6ee0ea456d02bd74f041c9299934176ec325e6;./kkk.xlsx

There are no headers and stuff, the only thing is the semicolon (;) character which delimites the fields.

Upvotes: 1

Views: 2959

Answers (2)

CB.
CB.

Reputation: 60910

With Array in a variable:

  $a | sort  {$_  -replace  "(.*;\./)", ''}

Upvotes: 5

Shay Levy
Shay Levy

Reputation: 126722

Convert the content to csv format, parse the content by semicolon delimiter, add headers and sort the output by the Path property:

@"
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855;./zzz.txt
d0c4c3e65c450251e44ec41c3c6ee0ea456d02bd74f041c9299934176ec325e6;./kkk.xlsx
9a1d469cdc7c2072b19a7e483a818c5e4e9de070298c60b34de29930e7b79209;./árvíztűrő tükörfúrógép/kkk - Shortcut.lnk
"@ | ConvertFrom-Csv -Header Checksum,Path -Delimiter ';' | Sort-Object Path


Checksum                                                                   Path                                                                      
--------                                                                   ----                                                                      
9a1d469cdc7c2072b19a7e483a818c5e4e9de070298c60b34de29930e7b79209           ./árvíztűrő tükörfúrógép/kkk - Shortcut.lnk                               
d0c4c3e65c450251e44ec41c3c6ee0ea456d02bd74f041c9299934176ec325e6           ./kkk.xlsx                                                                
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855           ./zzz.txt

Upvotes: 2

Related Questions