Skip to content

powershell 7.4 sort cmdlet sort différenlty from PS 5.1 cmdlet #21322

Closed

Description

@DcaCodes

Prerequisites

Steps to reproduce

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 :

'file.txt','file_h.txt' | sort 
file.txt 
file_h.txt 

with powershell 7.4.1 the result is :

'file.txt','file_h.txt' | sort 
file_h.txt
file.txt 

wich is not lexical order

Expected behavior

PS>'file.txt','file_h.txt' | sort
file.txt
file_h.txt

Actual behavior

PS>'file.txt','file_h.txt' | sort
file_h.txt
file.txt

Error details

No response

Environment data

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

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Mar 9, 2024
  2. 237dmitry commented on Mar 9, 2024

    @237dmitry

    I think this is for cross platform compatibility:

    $ 'file.txt','file_h.txt' | /usr/bin/sort
    file_h.txt
    file.txt
    

    bash:

    $ echo -e 'file.txt\nfile_h.txt' | sort
    file_h.txt
    file.txt
    
  3. 237dmitry commented on Mar 9, 2024

    @237dmitry

    your solution

    Did you mean to say "assumption"? If I wrote a solution, it could be like this:

    'file.txt','file_h.txt' | sort { [int[]][char[]] $_ }
    
  4. DcaCodes commented on Mar 9, 2024

    @DcaCodes
    Author

    Curious is when you add . to end of strings that result change

    PS C:\Users\dom> 'file','file_h' | Sort-Object
    file
    file_h
    PS C:\Users\dom> 'file','file_h.' | Sort-Object
    file
    file_h.
    PS C:\Users\dom> 'file.','file_h.' | Sort-Object
    file_h.
    file.
    PS C:\Users\dom> 'file.','file_h' | Sort-Object
    file_h
    file.
    

    the example can be simplified
    PowerShell 7.4.1

    '.','_' | Sort-Object -Culture en-US
    _
    .
    

    Powershell 5.1

    '.','_' | Sort-Object -Culture en-US
    .
    _
    

    note the -culture same result with fr-FR
    to hex

    '._' | format-hex
    
       Label: String (System.String) <7E9D5112>
    
              Offset Bytes                                           Ascii
                     00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
              ------ ----------------------------------------------- -----
    0000000000000000 2E 5F                                           ._
    

    How to explain this change of result ?

    I try linux on https://www.tutorialspoint.com/linux_terminal_online.php

    $ 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.
  5. 237dmitry commented on Mar 9, 2024

    @237dmitry

    Interestingly, if I add criteria for sorting, the sorting will work as expected

    $ 'h_','h.' | sort
    h_
    h.
    
    $ 'h_','h.' | sort fake
    h.
    h_
    
  6. mklement0 commented on Mar 9, 2024

    @mklement0
    Contributor

    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 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.

    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-Object to 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.

  7. mklement0 commented on Mar 9, 2024

    @mklement0
  8. 237dmitry commented on Mar 9, 2024

    @237dmitry

    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.

    $ locale
    LANG=en_US.UTF-8
    LC_CTYPE="en_US.UTF-8"
    LC_NUMERIC=en_US.UTF-8
    LC_TIME=en_US.UTF-8
    LC_COLLATE="en_US.UTF-8"
    LC_MONETARY=en_US.UTF-8
    LC_MESSAGES="en_US.UTF-8"
    LC_PAPER=en_US.UTF-8
    LC_NAME=en_US.UTF-8
    LC_ADDRESS=en_US.UTF-8
    LC_TELEPHONE=en_US.UTF-8
    LC_MEASUREMENT=en_US.UTF-8
    LC_IDENTIFICATION=en_US.UTF-8
    LC_ALL=
    
    $ sls '^[^#]' /etc/locale.gen -raw
    en_US.UTF-8 UTF-8
    
    $ Get-Culture
    
    LCID             Name             DisplayName
    ----             ----             -----------
    1033             en-US            English (United States)
  9. mklement0 commented on Mar 9, 2024

    @mklement0
  10. mklement0 commented on Mar 9, 2024

    @mklement0
  11. 237dmitry commented on Mar 10, 2024

    @237dmitry
  12. mklement0 commented on Mar 10, 2024

    @mklement0
  13. 237dmitry commented on Mar 11, 2024

    @237dmitry
  14. DcaCodes commented on Mar 11, 2024

    @DcaCodes
    Author
  15. mklement0 commented on Mar 11, 2024

    @mklement0
    Contributor

    237dmitry:

    After further research, I've concluded:

    • 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.

  16. mklement0 commented on Mar 11, 2024

    @mklement0
    Contributor

    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-Object printing _ first in PowerShell Core (across all platforms).

  17. mklement0 commented on Mar 12, 2024

    @mklement0
    Contributor

    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
    }

    Output:

    i I İ ı  # en-US
    ı I i İ  # tr-TR

    You can replicate the above at https://icu4c-demos.unicode.org/icu-bin/collation.html by pasting the following as input:

    i
    I
    ı
    İ
    

    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

  18. mklement0 commented on Mar 13, 2024

    @mklement0
    Contributor

    rhubarb-geek-nz, re the Stack Overflow post you mentioned:

    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.

  19. mklement0 commented on Mar 13, 2024

    @mklement0
    Contributor

    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.

      • As all cultural rules, ICU's rules are subject to change over time.

        • The above comment shows how to determine the specific ICU library version that is used on a given machine.
        • The ICU Locale Explorer allows interactive experimentation, albeit seemingly only based on the most recent ICU version.
  20. added
    Resolution-Answered
    and removed
    Needs-Triage
    on Mar 14, 2024
  21. microsoft-github-policy-service commented on Mar 15, 2024

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.

  22. microsoft-github-policy-service commented on Mar 15, 2024

    @microsoft-github-policy-service
    Contributor

    📣 Hey DcaCodes, how did we do? We would love to hear your feedback with the link below! 🗣️

    🔗 https://aka.ms/PSRepoFeedback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-Answered

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions