Line Filters in Groovy
Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. In this case, it writes a capitalized version of all input text. You can use this pattern to write your own Groovy line filters.
import java.util.Scanner
// Wrapping System.in with a Scanner gives us a convenient
// nextLine() method that reads the next line of input.
def scanner = new Scanner(System.in)
// Read each line of input
while (scanner.hasNextLine()) {
// Get the next line and convert it to uppercase
def ucl = scanner.nextLine().toUpperCase()
// Write out the uppercased line
println ucl
}
// Check for errors during reading
if (scanner.ioException()) {
System.err.println("Error: ${scanner.ioException()}")
System.exit(1)
}
To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then use the line filter to get uppercase lines.
$ cat /tmp/lines | groovy line-filters.groovy
HELLO
FILTER
In this Groovy version:
We use a
Scanner
to read input fromSystem.in
, which is similar to thebufio.Scanner
in the Go version.The
while
loop withhasNextLine()
is equivalent to thefor scanner.Scan()
loop in Go.We use the
toUpperCase()
method to convert each line to uppercase, similar tostrings.ToUpper()
in Go.Error handling is done by checking
scanner.ioException()
after the loop, which is similar to checkingscanner.Err()
in the Go version.We use
System.err.println()
to print error messages to stderr, equivalent tofmt.Fprintln(os.Stderr, ...)
in Go.
This Groovy script can be run directly without compilation, making it convenient for quick scripting tasks.