Using Groovy as a command-line text file editor

The groovy command, which we introduced in the Executing Groovy code from the command line recipe, can also be used as a stream editor or text file filter. In this recipe, we will cover the -i, -n, and -p parameters that can be used to leverage file editing and processing functionality.

How to do it...

Assume that you have a file, data.txt, which contains five lines with numbers from 1 to 5:

  1. To multiply each number by 2, you can use the following command:
    groovy -n -e "println line.toLong() * 2" data.txt
    
  2. We can even omit the println method call if we pass additional the -p parameter to the command:
    groovy -n -p -e "line.toLong() * 2" data.txt
    
  3. In both cases, Groovy will print the following output:

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.