You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am experiencing problems with the result of sort cmdlet.
Here a string array 'file.txt','file_h.txt'
I apply sort in it : 'file.txt','file_h.txt' | sort
with powershell 5.1 the result is :
Name Value
---------
PSVersion 7.4.1
PSEdition Core
GitCommitId 7.4.1
OS Microsoft Windows 10.0.19045
Platform Win32NT
PSCompatibleVersions {1.0,2.0,3.0,4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
$ touch h.
$ touch h_
$ ls | sort
h.
h_
$ uname -a
Linux c07a703aeb3b 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
Unix Online Terminal | Online Unix Compiler - The best online Unix compiler and editor which allows you to write Unix Code, Compile and Execute it online from your browser itself. You can create Unix Project using Unix version GNU Bash v4.4. You can also Edit, Save, Compile, Run and Share Unix Code online.
.NET's sorting behavior on Windows changed with .NET 5's move to cross-platform, ICU-based internationalization, as described in .NET globalization and ICU.
PowerShell v7.1+ is based on .NET 5+
As a side effect, the sort order of _ vs. . is now different relative to Windows PowerShell (based on .NET Framework, which uses Windows-specific NLS sorting rules): for instance, in the en-US culture _ sorts before . in PowerShell 7.1+, on all platforms, whereas in Windows PowerShell . sorts before _.
This not only affects Sort-Object, but also implicit sorting contexts such as the output order of Get-ChildItem and tab-completion order.
On Windows (only), an opt-in to the old behavior is available in .NET 5+ (see the linked documentation), but note that that would take effect session-globally in PowerShell and also change other culture-related behaviors.
Like Windows PowerShell, the sort utility on Unix-like platforms places . before _ e.g. in the en-US culture
('_', '.' | /usr/bin/sort); ditto for ls; these utilities build on system calls that do not use ICU, but on the so-called binary locale database, typically in /usr/lib/locale - see man 5 locale on Unix distros.
I don't know what governs the rules and how they compare to ICU, but they can vary from distro to distro and change over time (e.g., if additional characters that differ are present, they may override the . vs. _ sorting; e.g., printf '%s\n' _ . _a .b | /usr/bin/sort yields different results across distros / versions, with more recent versions prioritizing a and b, i.e. placing . before _ only if the input strings differ only by these chars.). As in both PowerShell editions, it is not ordinal sorting that is applied (e.g., e and é sort together) - unless you use the C / POSIX locale.
As for ordinal sorting in PowerShell (sorting strictly based on the Unicode code points of the characters that make up the input strings):
You must currently use .NET APIs directly to get reasonable performance, e.g., with [string[]] $arr = 'z'..'a' as input, and case-insensitive ordinal comparison:
[Array]::Sort($arr, [System.StringComparer]::OrdinalIgnoreCase) (sorts in place)
Sort-Object-based workarounds are possible, but perform poorly, e.g., the following is about two orders of magnitude slower (and is memory-inefficient):
I'm curious what your environment / locale / culture settings are that produce a different result.
Diiffrent where? In bash or in pwsh? bash sorting h. and h_ properly, but not file.txt and file_h.txt. If bash launched with --posix switch then result also proper.
Standard Unix utilities such as /usr/bin/sort as well as system calls are unrelated to ICU - they use distro-specific locale definitions typically stored in /usr/lib/locale
The differences observed in the output from printf '%s\n' _ . _a .b | /usr/bin/sort come down to differences in these locale definitions - it sounds like more recent versions of Linux distros exhibit the behavior where placing . before _ only applies if the input strings differ only by these characters.
I've updated the previous comment with a succinct summary, and I've hidden my subsequent comments - likewise I encourage you to hide yours.
DcaCodes, collation has culture-specific elements, and I don't actually know how the linked Unicode charts account for that.
Overall, collation is a complex matter.
In the realm of ICU, there's https://icu4c-demos.unicode.org/icu-bin/collation.html, where you can experiment with sorting, and which has a dropdown for culture selection, as well as numerous other parameters - I presume these demos are based on the latest ICU version.
As the Unicode standard itself, ICU continues to evolve, and on a given platform you can determine which specific version of the ICU library is being used as follows:
(Add-Type-PassThru -NameSpace net.same2u -Name Aux -UsingNamespace System.Reflection -MemberDefinition @' public static Version GetIcuVersion() { Type interopGlobalization = Type.GetType("Interop+Globalization, System.Private.CoreLib"); if (interopGlobalization != null) { MethodInfo methodInfo = interopGlobalization.GetMethod("GetICUVersion", BindingFlags.NonPublic | BindingFlags.Static); if (methodInfo != null) { int version = (int)methodInfo.Invoke(null, null)!; return new Version(version >> 24, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF); } } return new Version(0, 0, 0, 0); }'@)::GetIcuVersion()
Using the default settings seems to match the de facto behavior of Sort-Object with en-US,
but ICU and therefore .NET 5+ does exhibit culture-specific variations.
For instance, the infamous "Turkish i problem" results in different sorting of the various variants of the letter "i": i I ı İ:
& {
$prevCulture= [cultureinfo]::CurrentCulture
'en-US','tr-TR'|% {
[cultureinfo]::CurrentCulture =$_
(Write-Output i I ı İ |Sort-Object-CaseSensitive) -join''
}
[cultureinfo]::CurrentCulture =$prevCulture
}
and, with the culture dropdown list item at the default, und (type=standard) root (Standard Order), vs. tr (type=standard): Turkish (Standard Sort Order), clicking sort
While it indeed implies that Sort-Object does not perform ordinal sorting - instead, it performs linguistic sorting based on the current culture, case-insensitively by default ([StringComparer]::CurrentCultureIgnoreCase) - the other issues discussed there, while interesting, are incidental to the discussion here.
I've posted an answer there that clarifies the fundamentals and also explains the incidental issues.
Let me try to provide a succinct summary here, which hopefully brings closure to the issue at hand as well as the aforementioned near/effective duplicates:
Sort-Object uses linguistic sorting based on the current culture, case-insensitively by default ([StringComparer]::CurrentCultureIgnoreCase); case-sensitivity is opt-in, via -CaseSensitive ([StringComparer]::CurrentCulture), and the culture context can be altered ad hoc with a -Culture argument (use 127 to request the invariant culture).
In v7.1+ / .NET 5+, it is the ICU library that provides the collation (sorting) rules - PowerShell merely surfaces the underlying .NET behavior.
These ICU-based rules differ both from earlier versions on Windows and Windows PowerShell, and notably also from the native sorting rules on Unix-like platforms, such as exhibited by /usr/bin/sort
This discrepancy is unfortunate, especially in the context of sorting of file-system items, where the now-frustrated expectation is that . sorts before _, but unlikely to change.
On the plus side, it results in consistent cross-platform behavior, assuming the same ICU library version (see next point); that said, new library versions often bring only additive and minor changes.
Activity
237dmitry commentedon Mar 9, 2024
I think this is for cross platform compatibility:
bash:
237dmitry commentedon Mar 9, 2024
Did you mean to say "assumption"? If I wrote a solution, it could be like this:
DcaCodes commentedon Mar 9, 2024
Curious is when you add
.to end of strings that result changethe example can be simplified
PowerShell 7.4.1
Powershell 5.1
note the
-culturesame result with fr-FRto hex
How to explain this change of result ?
I try linux on https://www.tutorialspoint.com/linux_terminal_online.php
237dmitry commentedon Mar 9, 2024
Interestingly, if I add criteria for sorting, the sorting will work as expected
mklement0 commentedon Mar 9, 2024
PowerShell is only the messenger here:
.NET's sorting behavior on Windows changed with .NET 5's move to cross-platform, ICU-based internationalization, as described in .NET globalization and ICU.
PowerShell v7.1+ is based on .NET 5+
As a side effect, the sort order of
_vs..is now different relative to Windows PowerShell (based on .NET Framework, which uses Windows-specific NLS sorting rules): for instance, in the en-US culture_sorts before.in PowerShell 7.1+, on all platforms, whereas in Windows PowerShell.sorts before_.This not only affects
Sort-Object, but also implicit sorting contexts such as the output order ofGet-ChildItemand tab-completion order.On Windows (only), an opt-in to the old behavior is available in .NET 5+ (see the linked documentation), but note that that would take effect session-globally in PowerShell and also change other culture-related behaviors.
Like Windows PowerShell, the
sortutility on Unix-like platforms places.before_e.g. in the en-US culture(
'_', '.' | /usr/bin/sort); ditto forls; these utilities build on system calls that do not use ICU, but on the so-called binary locale database, typically in/usr/lib/locale- seeman 5 localeon Unix distros.I don't know what governs the rules and how they compare to ICU, but they can vary from distro to distro and change over time (e.g., if additional characters that differ are present, they may override the
.vs._sorting; e.g.,printf '%s\n' _ . _a .b | /usr/bin/sortyields different results across distros / versions, with more recent versions prioritizingaandb, i.e. placing.before_only if the input strings differ only by these chars.). As in both PowerShell editions, it is not ordinal sorting that is applied (e.g.,eandésort together) - unless you use theC/POSIXlocale.For more information, see:
As for ordinal sorting in PowerShell (sorting strictly based on the Unicode code points of the characters that make up the input strings):
You must currently use .NET APIs directly to get reasonable performance, e.g., with
[string[]] $arr = 'z'..'a'as input, and case-insensitive ordinal comparison:[Array]::Sort($arr, [System.StringComparer]::OrdinalIgnoreCase)(sorts in place)Sort-Object-based workarounds are possible, but perform poorly, e.g., the following is about two orders of magnitude slower (and is memory-inefficient):$sortedArr = $arr | Sort-Object { -join ([int[]] [char[]] $_.ToLower()).ForEach({ $_.ToString('x4') }) }Enhance some cmdlets with Culture and Comparison parameters #9348 asks for a number of cmdlets, including
Sort-Objectto be enhanced so as to support ordinal sorting on demand, along with an associated RFC, Enhance some cmdlets with Culture parameter PowerShell-RFC#167. Unfortunately, activity has stalled quite a while ago.mklement0 commentedon Mar 9, 2024
237dmitry commentedon Mar 9, 2024
Diiffrent where? In bash or in pwsh? bash sorting
h.andh_properly, but notfile.txtandfile_h.txt. If bash launched with--posixswitch then result also proper.mklement0 commentedon Mar 9, 2024
mklement0 commentedon Mar 9, 2024
237dmitry commentedon Mar 10, 2024
mklement0 commentedon Mar 10, 2024
237dmitry commentedon Mar 11, 2024
DcaCodes commentedon Mar 11, 2024
it seems that order can be view here https://www.unicode.org/charts/collation/
specialy : https://www.unicode.org/charts/collation/chart_Punctuation.html
mklement0 commentedon Mar 11, 2024
237dmitry:
After further research, I've concluded:
Standard Unix utilities such as
/usr/bin/sortas well as system calls are unrelated to ICU - they use distro-specific locale definitions typically stored in/usr/lib/localeThe differences observed in the output from
printf '%s\n' _ . _a .b | /usr/bin/sortcome down to differences in these locale definitions - it sounds like more recent versions of Linux distros exhibit the behavior where placing.before_only applies if the input strings differ only by these characters.I've updated the previous comment with a succinct summary, and I've hidden my subsequent comments - likewise I encourage you to hide yours.
mklement0 commentedon Mar 11, 2024
Thanks, DcaCodes, https://www.unicode.org/charts/collation/chart_Punctuation.html indeed shows that
_sorts before.based on the Unicode collation order, as reflected in'.', '_' | Sort-Objectprinting_first in PowerShell Core (across all platforms).mklement0 commentedon Mar 12, 2024
DcaCodes, collation has culture-specific elements, and I don't actually know how the linked Unicode charts account for that.
Overall, collation is a complex matter.
In the realm of ICU, there's https://icu4c-demos.unicode.org/icu-bin/collation.html, where you can experiment with sorting, and which has a dropdown for culture selection, as well as numerous other parameters - I presume these demos are based on the latest ICU version.
As the Unicode standard itself, ICU continues to evolve, and on a given platform you can determine which specific version of the ICU library is being used as follows:
Using the default settings seems to match the de facto behavior of
Sort-Objectwithen-US,but ICU and therefore .NET 5+ does exhibit culture-specific variations.
For instance, the infamous "Turkish i problem" results in different sorting of the various variants of the letter "i":
i I ı İ:Output:
You can replicate the above at https://icu4c-demos.unicode.org/icu-bin/collation.html by pasting the following as input:
and, with the culture dropdown list item at the default,
und (type=standard) root (Standard Order), vs.tr (type=standard): Turkish (Standard Sort Order), clickingsortmklement0 commentedon Mar 13, 2024
rhubarb-geek-nz, re the Stack Overflow post you mentioned:
While it indeed implies that
Sort-Objectdoes not perform ordinal sorting - instead, it performs linguistic sorting based on the current culture, case-insensitively by default ([StringComparer]::CurrentCultureIgnoreCase) - the other issues discussed there, while interesting, are incidental to the discussion here.I've posted an answer there that clarifies the fundamentals and also explains the incidental issues.
mklement0 commentedon Mar 13, 2024
Let me try to provide a succinct summary here, which hopefully brings closure to the issue at hand as well as the aforementioned near/effective duplicates:
Sort-Objectuses linguistic sorting based on the current culture, case-insensitively by default ([StringComparer]::CurrentCultureIgnoreCase); case-sensitivity is opt-in, via-CaseSensitive([StringComparer]::CurrentCulture), and the culture context can be altered ad hoc with a-Cultureargument (use127to request the invariant culture).Sort-Objectcurrently unfortunately does not support ordinal sorting (see the stalled issue Enhance some cmdlets with Culture and Comparison parameters #9348).In v7.1+ / .NET 5+, it is the ICU library that provides the collation (sorting) rules - PowerShell merely surfaces the underlying .NET behavior.
These ICU-based rules differ both from earlier versions on Windows and Windows PowerShell, and notably also from the native sorting rules on Unix-like platforms, such as exhibited by
/usr/bin/sortThis discrepancy is unfortunate, especially in the context of sorting of file-system items, where the now-frustrated expectation is that
.sorts before_, but unlikely to change.On the plus side, it results in consistent cross-platform behavior, assuming the same ICU library version (see next point); that said, new library versions often bring only additive and minor changes.
As all cultural rules, ICU's rules are subject to change over time.
microsoft-github-policy-service commentedon Mar 15, 2024
This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.
microsoft-github-policy-service commentedon Mar 15, 2024
📣 Hey DcaCodes, how did we do? We would love to hear your feedback with the link below! 🗣️
🔗 https://aka.ms/PSRepoFeedback