Filtering a text file's content

Filtering a text file's content is a rather common task. In this recipe, we will show how it can be easily achieved with Groovy.

Getting ready

Let's assume we want to filter out comment lines from a Bash script stored in the script.sh file and we want to save it into the new_script.sh file. First of all, we need to define two variables of the java.io.File type that point to our inputFile and outputFile:

def inputFile = new File('script.sh')
def outputFile = new File('new_script.sh')

How to do it...

File filtering can be implemented in several ways:

  1. We can make use of the closure-based methods (that is eachLine and withPrintWriter) that we have got familiar with in the Reading a text file line by line and Writing to a ...

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.