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="filename.properties" token="@@@mytoken@@@" value="newValue" />

Thank you

Hi Firas,

the example stated below can be found at http://www.gradle.org/docs/current/userguide/userguide_single.html#filterOnCopy

import org.apache.tools.ant.filters.FixCrLfFilter

import org.apache.tools.ant.filters.ReplaceTokens

task filter(type: Copy) {

from ‘src/main/webapp’

into ‘build/explodedWar’

// Substitute property references in files

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

expand(project.properties)

// Use some of the filters provided by Ant

filter(FixCrLfFilter)

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

// Use a closure to filter each line

filter { String line ->

“[$line]”

}

}

For more explanation, see e.g. http://chimera.labs.oreilly.com/books/1234000001741/ch01.html#_keyword_expansion

HTH, M.

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

http://www.gradle.org/docs/current/dsl/org.gradle.api.tasks.Exec.html for more information on exec task.

hhhh

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:

replace('namefile')
 filter{....}

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)
}
2 Likes