특정 디렉토리 밑에 있는 파일 중에서 일정시간이 지난 파일을 삭제하고자 할 때 필요한 스크립트이다. 파일 서버를 관리하다보면, 주기적으로 필요 없는 파일들을 삭제해야 하는데, Unix(Linux) 환경에서는 find, rm 등을 조합하여 사용할 수도 있다. 그런 것이 여의치 않고, 굳이 Groovy 를 이용하려고 할 때, 활용하면 좋겠다.
final DAY_LIMIT = 2 // N일
final TARGET_DIR = "./"

println("[Deleted Files]\n")
new File(TARGET_DIR).eachFileRecurse { file ->
    if( file.file ) {
        def lastModified = new Date(file.lastModified())
        def diffDay = new Date() - lastModified
        if(diffDay > DAY_LIMIT) {
            println(lastModified.format("YYYY-mm-dd") + " : $file")
            file.delete()
        }
    }
}



Groovy에서 md5sum 을 구하려면, Java 의 MessageDigest 모듈을 이용해야 한다. 안타깝게도 file 에 대한 md5 checksum 을 구하는 부분은 구현되어 있지 않기 때문에 별도로 구현해야 한다. 다른 언어에서의 방법과 유사하므로 그리 어렵지는 않다. Java 의 모듈을 그대로 이용해야하기 때문에, 구현은 Java 의 그것과 거의 같다.
import java.security.MessageDigest
 
def md5sum(final file) {
    MessageDigest digest = MessageDigest.getInstance("MD5")
    file.withInputStream() { is ->          
        byte[] buffer = new byte[8192]
        int read = 0
        while( (read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
    }                                                        
    byte[] md5 = digest.digest()
    BigInteger bigInt = new BigInteger(1, md5)
    return bigInt.toString(16).padLeft(32, '0')
}
 
println md5sum(new File("md5sum.groovy"))



Groovy에서 하위 디렉토리의 모든 파일을 출력하는 방법을 알아보자. 인터넷에서 검색하면 금방 나오는 내용이지만, 일단 적어둔다.

new File("C:\\").eachFileRecurse { filename -> 
    println "Filename: $filename"
}




Ruby에서 파일(디렉토리)이름에 특정 문자열이 포함된 목록 출력하기위해서 아래와 같이 하면 된다. Unix(Linux)/Cygwin 에서는 기본적인 도구만으로도 쉽게 할 수 있지만, 그런 환경에 안되는 곳에서는 유용하다. 아주 사소한 팁이지만, 이런 것이 여러가지가 모이면, 나중에 큰 도움이 될 것이다. ^^

# -*- coding: cp949 -*-
require 'find'
 
$dirlist    = ["C:\\"]
$sub_string = "애니메이션"
 
$dirlist.each() do |dirname|
  puts dirname if dirname.include?($sub_string)
 
  Find.find(dirname) do |file|
    next if file == nil
    next if not File.file?(file)
    next if not file.include?($sub_string)
 
    puts file
  end
end


+ Recent posts