LoginSignup
3
3

More than 5 years have passed since last update.

【Groovy】ファイル名を規則に従って一括変換する【小人さんスクリプト】

Posted at

デザイナさんからもらった画像群が命名規則に従っているんだけれど、その命名規則が違うみたいな時ってありませんか?

その際に使えるGroovyスクリプトです。

下記のような変換を、プロジェクトルートのimagesディレクトリ以下を対象に行います。

「img_orange_1.png」->「character_orange_000.png」
「img_yellow_12.png」->「character_yellow_011.png」

「img_{TYPE}_{INDEX}.png」

という名前を

「character_{TYPE}_{変換後のINDEX}.png」

にします。

変換後のINDEXとは、もとのINDEXを

  • 3桁0で右うめ
  • INDEXは1始まりでなく0始まり

というルールで変換したものです。

def regex = /img_(.+)_(\d+).png/

new File("images").eachFile { file ->
    if(file.name ==~ regex) {
        (file.name =~ regex).each { fileName, type, index ->
            def updatedIndex = index.toInteger() - 1
            def updatedIndexString = updatedIndex.toString().padLeft(3, '0')
            def updatedFileName = "images/character_${type}_${updatedIndexString}.png"

            file.renameTo(updatedFileName)
        }
    }
};
3
3
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
3
3