Replacing tabs with spaces in a text file
Searching and replacing file content is an often needed routine that can be automated with the help of Groovy scripts, one of which will be shown in this recipe.
Getting ready
Let's assume that we have an input.txt
file that contains some tabulation characters. We want to replace the tabulation characters with spaces and save the results into a output.txt
file.
To perform any action on these files (similar to the Filtering a text file's content recipe), we need to create two instances of java.io.File
objects:
def inputFile = new File('input.txt') def outputFile = new File('output.txt')
How to do it...
Let's go through several ways to achieve the desired result:
First of all, we will take advantage of the
transformLine
method available in thejava.io.Reader
class, as well as thewithWriter
andwithReader
methods that are described in more detail in the Writing to a file and Reading from a file recipes:outputFile.withWriter { Writer writer -> inputFile...