0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

フォルダ上のファイル・フォルダの数値を0埋めする

Posted at

フォルダ上でファイルに番号を付けた管理するようなことがあると思います。
で、「この時このぐらいの桁数で足りるやろ」とか思ってたらファイルが増えて桁数が足りない。。。なんてことがありますよね?

※こんな感じ

Windowsのエクスプローラーは優秀(?)なのでこの場合も順番に並んでくれますが、
CLIを使用すると1,10,2,3,4,..の順で並んでしまったりするので改めて数値の0梅をしたいなんてことがあると思います。

今回はのためのPowershellスクリプトを作成したので紹介したいと思います。

早速スクリプト本体

Zerorename.ps1
# 引数設定箇所
# $Digits: 0埋め後の桁数指定(デフォルトは3桁)
# $TargetDir: 0埋め対象ファイルのあるディレクトリ.未指定の場合カレントディレクトリ
Param(
    [int]$Digits=3,
    $TargetDir=(Get-Location).Path
)

# ゼロ埋めの桁数を変数指定
# 0の数が数値変換のフォーマットになる
$Zeropadding = "0" * $Digits

# 対象ファイル一覧取得
# 一覧に対して処理を実行
foreach($f in Get-ChildItem -Name ${TargetDir}){
    # ファイルに含まれる整数値を取得
    $NumberList = [regex]::Matches($f,"\d+")
    
    # 探索した数値の位置それぞれに対して0埋め後の数値に置き換える処理
    # 元の数値が定義した桁数以上の場合は置き換えない。
    $filename=""
    $before=-1
    foreach($qp in $NumberList){
        if ($qp.Length -ge $Digits){
            continue
        }
        $filename=$filename + $f.Substring($before + 1,$qp.Index - $before -1) + ([int]($qp.value)).ToString($Zeropadding)
        $before=$qp.Index + $qp.Length - 1
    }
    $filename=$filename + $f.Substring($before + 1)
    
    # 0埋め後のファイル名が元のファイル名と一致した場合は後続のリネーム処理をスキップ
    if ($f -eq $filename){
        continue
    }
    
    # リネーム処理
    try{
        Rename-Item -Path ${TargetDir}\${f} -NewName ${TargetDir}\${filename}
        write-output "Rename file. From:${TargetDir}\${f} , To:${TargetDir}\${filename}"
    }catch {
        write-output "Failed File rename. Target file : ${TargetDir}\${f}"
        write-putput $_
     }
}

スクリプトの使い方と仕様

PS> .\Zerorename.ps1 -Digit <0埋め後の桁数> -TargetDir <対象フォルダ>

0埋め後の桁数 : 任意の整数を入力してください。未指定でも稼働し、その場合は3桁になります。※3桁の場合1⇒001とリネームされます。
対象フォルダ : 対象ファイルが存在するふぉるだを指定してください。未指定の場合はカレントディレクトリで動作します。

  • 指定したフォルダ上のファイル/フォルダの数値を指定した桁数で0埋めしてリネームします。
     例: 1_test.txt ⇒ 001_test.txt
  • ファイル/フォルダに数値が含まれていない場合はリネームされません。
  • ファイルに複数の数値が含まれている場合はそれぞれの数値が0埋めされます。
     例: 1_02_12_test.txt ⇒ 001_002_012_test.txt
  • 含まれている数値が指定した桁数より大きい場合はその個所はリネームされません。
     例: 1_0088_test.txt ⇒001_0088_test.txt

動作確認

こんな感じのファイルを用意して実行してみる。

実行

うまく変更された。
※007_test.txtは変更されないのでログに出てきません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?