Groovy Text File Pattern Substitution

I needed to substitute all the patterns “${any letter}” with some predefined replacement strings today, and the pattern could appear any times on the same line. This is the code snippet I came up in Groovy to complete the mission.

def replacePatterns(inputFile, outputFile)
{
  def patternsToSubstitue=[
  /*  */'${aaa}':"3a",
  /*  */'${bbbb}':"4b",
  /*  */]

  outputFile.withWriter
  { writer ->
    inputFile.eachLine
    { line ->
      println("Processing line: $line" );
      def result=line
      line.findAll(/\$\{[^\$]*\}/).each
      {
        result=result.replace(it, patternsToSubstitue[it])
      }
      println("Processed result line: $result" );
      writer << result+System.getProperty("line.separator")
    }
  }
}

Given an input file with the following two lines

This line has none
This line has ${aaa} and ${bbbb}

The code can create an output file containing

This line has none
This line has 3a and 4b

Advertisements
This entry was posted in Groovy, Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s