Replace tokens in file

Hello, can anyone explain us how to replace tokens in a file or collections of files. I look for something equivalent to this code in ant:

<replace file="" token="@@@mytoken@@@" value="newValue" />

Thank you

Hi Firas,

the example stated below can be found at



task filter(type: Copy) {

from ‘src/main/webapp’

into ‘build/explodedWar’

// Substitute property references in files

expand(copyright: ‘2009’, version: ‘2.3.1’)


// Use some of the filters provided by Ant


filter(ReplaceTokens, tokens: [copyright: ‘2009’, version: ‘2.3.1’])

// Use a closure to filter each line

filter { String line ->




For more explanation, see e.g.


Thank you Marian for your answer, I know how to replace tokens with the copy task, but what I would like to do is directly replace the tokens in a file without have to call the copy task.

Can you elaborate?

You can use ant tasks natively, so try to use this:

ant.replace(file: ‘index.html’, token: ‘@@@’, value: ‘wombat’)

Other approach would be to call an external application - e.g. awk/sed - to do the job - see for more information on exec task.


I know that also, is there a pure gradle fonctions to do that? If not I will take the ant task solution Thank you again Marian

OK, as far as I know there is no such dedicated functionality in Gradle (as ant is a first class citizen in it)

Anyway, can you still elaborate why do you need this?

Simply I just look to replace a token in file, without have to copy and rewrite it. Something like:


Never mind, I have just thought that this function exist. Thank you

Let’s say more gradle natural way would be still to use a copy task for it, and then just manipulate the transformed “target” - at least it gives you the ability to skip the manipulation if the source hasn’t changed… (you should even chain tasks this way - use the ouput of a task and get it as an input of another one…)

And that was also the reason we asked for context - just because a manipulation on a file doesn’t seem to be a task for any build tool…

I like the following way:

filter {
    it.replace('${launch_urls}', launchUrls.join("<br>\n"))
      .replace('${name}', project.ext.mName)
      .replace('${version}', project.ext.mCurrentVersion)