Substitute variables in a String read from a file using Groovy

72 views Asked by At

New to groovy as part of upskilling, please help. I have a text file with content below:

Name is $vName City is $vCity

I read this file as follows.

def vName="John" 
def vCity="NewYork"
def fData = readFile(file: "c:\data.txt")
print fData

I would need to replace the variables vName and vCity with its values and print them. Is there a way i can get the variables resolved ?

I have executed the script. but it does not work

1

There are 1 answers

2
Paul King On

Here is how it could be solved with SimpleTemplateEngine:

// declare your file (we'll use a temp file and set example content)
def file = File.createTempFile('template', 'file')
file.text = 'Name is $vName City is $vCity'
// example variables added to binding
vName="John"
vCity="NewYork"
// use simple template engine
def engine = new groovy.text.SimpleTemplateEngine()
file.withReader { reader ->
    def template = engine.createTemplate(reader).make(binding.variables)
    assert template.toString() == 'Name is John City is NewYork'
}