Dark theme | Light theme

October 10, 2009

Groovy Goodness: Using Groovy on the Command-Line

We can use Groovy on the command-line to evaluate one-line scripts and pipe output to other commands or use input from other commands. This makes for some command-line scripting. We invoke groovy with the -e argument to evaluate a simple script. We can even use arguments in the script.

Other arguments are -n and -p to process each line of input from a file or from another command. We can also iterate over a list of files, change the contents and use the -i argument to define a backup file pattern when saving the files.

The last argument is -l to start Groovy in listening mode. We can use for example a telnet client to connect to groovy and do some processing.

// Pipe groovy output to grep.
$ groovy -e "Locale.availableLocales.each { println it.displayName }" | grep English

// Or do it all in Groovy.
$ groovy -e "Locale.availableLocales.displayName.findAll { it =~ args[0] }.each { println it }" English

// Using -n and -p to filter each line.
$ groovy -e "Locale.availableLocales.each { println it.displayName }" | groovy -ne "if (line =~ 'English') println line"
$ groovy -e "Locale.availableLocales.each { println it.displayName }" | groovy -pe "if (line =~ 'English') line"

// All will output:
English (United States)
English (Malta)
English (United Kingdom)
English (New Zealand)
English (Philippines)
English (South Africa)
English (Ireland)
English (India)
English (Australia)
English (Canada)
English (Singapore)

Starting Groovy in listening mode:

$ groovy -l 9000 -e "println 'You say: ' + line"
groovy is listening on port 9000

$ telnet localhost 9000
Connected to localhost.
Escape character is '^]'.
Groovy Rocks!
You say: Groovy Rocks!