Groovy: 파일 재귀적으로 이름 바꾸기
게시: 29 July 2019
제 TV의 비디오 플레이어는 넘기는 방식이 독특하네요
연속 읽기로 파일 간에
그리고 재생 모드는 1….mp4에서 10….mp4로 넘어가는 것입니다.
1…mp4`에서 `2….mp4`까지가 아니라.
문제는 파일과 폴더가 거의 900개에 달한다는 점입니다.
Bingo, 조작을 위한 Groovy의 아주 멋진 활용 사례입니다
파일, 이름 변경, 파일 이름의 패턴 검색
또는 폴더.
여기서 목표는 다음으로 시작하는 이름을 변경하는 것입니다
숫자이며 이름의 두 번째 문자가
숫자가 아니므로, 이 이름 앞에 0을 추가하겠습니다
renameFilesToStartWithTwoDigit.groovy
#!/usr/bin/env groovy
/**
* get a crossplateform separator
* @return
*/
static String getSeparator() {
System.getProperty("file.separator")
}
/**
* rename file
* @param file
* @param newName
* @return the renamed file
*/
static File rename(File file, String newName) {
assert file.renameTo(file
.parentFile.path +
getSeparator() +
newName)
new File(file
.parentFile.path +
getSeparator() +
newName)
}
String rootFolderPath = System.getProperty("user.home") +
"/Bureau/ng-courses/Udemy - Angular 7 " +
"(formerly Angular 2) - The Complete Guide"
File rootFolder = new File(rootFolderPath)
assert rootFolder.exists()
assert rootFolder.directory
assert rootFolder.canRead()
List<File> dirList = new ArrayList<>()
//Adding rootFolder in dirList
// just in case there is some files in it
dirList.add(rootFolder)
//looping to get list of directories
//recursively inside rootFolder
rootFolder.traverse { File file ->
!file.directory ?: dirList.add(file)
}
//looping through dirList
//to rename directories filling criterias
for (int i = dirList.size() - 1; i >= 0; i--) {
Character[] chars = dirList.get(i).name.chars
!(chars[0].digit && !chars[1].digit) ?:
dirList.set(i, rename(dirList.get(i),
"0${dirList.get(i).name}"))
if (dirList.get(i).directory) {
//looping through directory
//to rename file filling criterias
dirList.get(i).listFiles().each { File f ->
Character[] cs = f.name.chars
!(cs[0].digit && !cs[1].digit) ?:
rename(f, "0${f.name}")
}
}
}