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:

  1. We use a Scanner to read input from System.in, which is similar to the bufio.Scanner in the Go version.

  2. The while loop with hasNextLine() is equivalent to the for scanner.Scan() loop in Go.

  3. We use the toUpperCase() method to convert each line to uppercase, similar to strings.ToUpper() in Go.

  4. Error handling is done by checking scanner.ioException() after the loop, which is similar to checking scanner.Err() in the Go version.

  5. We use System.err.println() to print error messages to stderr, equivalent to fmt.Fprintln(os.Stderr, ...) in Go.

This Groovy script can be run directly without compilation, making it convenient for quick scripting tasks.