Skip to content

Instantly share code, notes, and snippets.

@alantsai
Created February 1, 2017 16:10
Show Gist options
  • Save alantsai/07be13d4520cdd4c4f421b9fe356d618 to your computer and use it in GitHub Desktop.
Save alantsai/07be13d4520cdd4c4f421b9fe356d618 to your computer and use it in GitHub Desktop.
use powershell to sort file by using natural number #powershell

有時候檔案名稱裡面會有數字,但是排序的時候因為是用字串排序,所以順序不如預期。 例如說有以下幾個檔案:

a1
a2
a10
a20

預期的排序應該如上,但是實際上排序出來會類似:

a1
a10
a2
a20

這個時候,個億透過powershell用regex的方式把數字的部分填充讓整個排序正常

原始資訊是:http://stackoverflow.com/questions/5427506/how-to-sort-by-file-name-the-same-way-windows-explorer-does

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

這個時候要注意通常資料夾名稱Windows預設使用括弧,所以像是(1),這個時候上面的方式可能不好用 這個時候建議可以把括弧替換掉,可以用:

Rename-Item –NewName { $_.name.replace(' ','_') -replace '[()]','_' }

整個搭配起來可以這樣:

  1. 先把括弧換成底線_
  2. 用數字排序方式把建立時間替換 - 最後外部排序可以用日期來排 - 避免掉要改名稱
$filePath = "C:\path\to\file"

dir $filePath | Rename-Item –NewName { $_.name.replace(' ','_') -replace '[()]','_' }

dir $filePath | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(20) }) } | 
%{$index=1}{ Set-FileTimeStamps -path $_.FullName -date  $($(get-date).AddMinutes($index).ToString("yyyy-MM-dd HH:mm:ss")); $index = $index+10}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment