-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Groovy 2 Cookbook
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.
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')File filtering can be implemented in several ways:
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 file recipes:
outputFile.withPrintWriter { writer ->
inputFile.eachLine { line ->
if (!line.startsWith('#')) {
writer.println(line)
}
}
}Another way to achieve the same result is to use a filterLine method. It takes a Writer and...
Change the font size
Change margin width
Change background colour