Skip to content

Instantly share code, notes, and snippets.

@markwragg
Last active February 5, 2024 12:16
Show Gist options
  • Save markwragg/e2a9dc05f3464103d6998298fb575d4e to your computer and use it in GitHub Desktop.
Save markwragg/e2a9dc05f3464103d6998298fb575d4e to your computer and use it in GitHub Desktop.
PowerShell natural sort. A regex way to sort files that have a number in them correctly, e.g rather than img1, img10, img11, img2, -> img1, img2, img10, img11
# http://stackoverflow.com/a/5429048/2796058
$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
Get-ChildItem | Sort-Object $ToNatural
@PureOcean
Copy link

One-line in CMD:

powershell -Command "(Get-ChildItem | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(9999) }) }).Name"

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