Numerical sorting?

This topic contains 5 replies, has 5 voices, and was last updated by  Dan Potter 1 year, 8 months ago.

  • Author
    Posts
  • #33810

    Mica
    Participant

    Is there any method of sorting files numerically as in 1,2,3..9,10,11, as opposed to literally, as in 1,10,11,2,3,4..?

  • #33824

    Dave Wyatt
    Moderator

    You'd have to convert those strings to numbers first, and how you do that will depend on what else is in the file name. (is it just 1.txt, 2.txt, etc? Or file-1.txt, etc?)

  • #33834

    Dan Potter
    Participant

    gci |Sort-Object { [int]$_.basename }

  • #33842

    Richard Siddaway
    Moderator

    Can't rely on only numbers in file name

    PS> [int]file01.txt
    At line:1 char:6
    + [int]file01.txt
    + ~~~~~~~~~~
    Unexpected token 'file01.txt' in expression or statement.
    + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

  • #33865

    Mica
    Participant

    This will sort the file names that contain numbers, but makes everything else go out of order:

    Get-ChildItem | Sort-Object {$_.BaseName -replace "\D+" -as [Int]}

    I tried a few things like this, but no luck:

    Sort-Object {If ($_.BaseName -match '\d+' -eq "True") {$_.BaseName -replace "\D+" -as [Int]}}

    So I'm guessing it's not possible to selectively sort only certain objects. At least not in one line.

  • #33878

    Dan Potter
    Participant

    I was giving you something to go on. We still need to know what you're working with to give an accurate answer.

    I can only assume you're writing logs with similar names and the int. For that I'd just sort by last write time.

You must be logged in to reply to this topic.