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",
  /*  */]

  { writer ->
    { line ->
      println("Processing line: $line" );
      def result=line
        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

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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s