Saturday, December 5, 2015

Use Gradle to remove 2-digits prefix in filenames recursively


What we have:




We want to remove all the number prefixes in the songs' names. Something like this




import groovy.io.FileType

FileCollection collection
File srcDir = new File('Taylor Swift')

task rename {


    println 'pwd'.execute().text

    def list = []


    srcDir.eachFileRecurse(FileType.FILES) { file ->
        list << file
    }
    list.each {
        changeName(it)
    }
}


def changeName(File file) {

    String regex = "^[0-9][0-9].*"    String originalName = file.getName()



    boolean b = originalName.matches(regex);

    if (b) {
        String newname = originalName.replaceFirst("[0-9][0-9]\\s", "")
        File newNameFile = new File(file.getParent(), newname)
        file.renameTo(newNameFile)

        println newNameFile

    }


}

No comments:

Post a Comment