Groovy CLI
|
|
|
gilbird.com wiki
CLI(Command Line Interface)에서 Groovy 쓰기
쉘에서 groovy나 groovy.bat 커맨드로로 간편하게 Groovy 언어를 사용할 수 있다.
$ groovy -help
usage: groovy [options] [args]
options:
-a,--autosplit <splitPattern> split lines using splitPattern (default '\s')
using implicit 'split' variable
-c,--encoding <charset> specify the encoding of the files
-D,--define <name=value> define a system property
-d,--debug debug mode will print out full stack traces
-e <script> specify a command line script
-h,--help usage information
-i <extension> modify files in place; create backup if
extension is given (e.g. '.bak')
-l <port> listen on a port and process inbound lines
-n process files line by line using implicit
'line' variable
-p process files line by line and print result
(see also -n)
-v,--version display the Groovy and JVM versions
Groovy 스크립트는 쉘에서 바로 실행해볼 수 있다.
$ cat test.groovy println 'Hello Bonson' $ groovy test.groovy Hello Bonson
다음은 커맨드 라인 인자를 사용하는 예이다.
$ cat test.groovy println 'Hello ' + args[0] $ groovy test.groovy Jeeves Hello Jeeves
커맨드 라인 인자에 스크립트를 넣어서 간단하게 실행해볼 수도 있다.
$ groovy -e "println 'Hello Bob'" Hello Bob
이 방식이 유용하지 않을 것처럼 보이겠지만 유닉스에서 커맨드 조합을 한다면 강력하게 써먹을 수 있다.
관련 툴로 perl, sed, awk, grep등이 애용되는데 보통 유닉스에 익숙한 사용자가 아니라면
이 툴로 만든 커맨드를 보면 알아보기 힘들 텐데 자바와 친하다면 그루비를 비슷하게 써먹을 수있다.
$ grep -i ^groov /usr/share/dict/words | groovy -e 'print System.in.text.toUpperCase()' GROOVE GROOVELESS GROOVELIKE GROOVER GROOVERHEAD GROOVINESS GROOVING GROOVY
STDIN이나 입력파일을 받아서 반복 처리하는 방식은 빈번하게 사용하여 groovy (ruby, perl 등도 동일)에서는 간편한 방식을 제공한다.
-n 옵션을 넣으면 입력 각 라인으로 루프를 돌아서 line 변수를 스크립트에서 쓸 수 있도록 제공한다.
grep -i ^groov /usr/share/dict/words | groovy -n -e 'println line.toUpperCase()'
각 라인 결과를 무조건 출력하고 싶다면 -p 옵션으로 소스가 더 간단해진다.
grep -i ^groov /usr/share/dict/words | groovy -p -e 'line.toUpperCase()'
-i 옵션으로 루프를 돌면 원본 파일에 결과를 쓰기하고 지정한 확장자로 백업본을 생성한다.
다음은 파일 전체 탐색하여 변환하는 예이다.
groovy -p -i .bak -e '(line =~ "<h\\d>(.*)</h\\d>").replaceAll("$1")' ~/Desktop/cooluri.html
-i 옵션에 백업 확장자는 꼭 써야 하는데 응용으로 다음과 같이 쓸 수도 있다.
find . -name \*.java | xargs groovy -p -i -e '(line =~ "@author James Strachan").replaceAll("@author Bobby Bonson")'
더많은 예제와 힌트는 Perl One Liners 검색결과를 살펴보기 바란다.