Search code examples
gradletoken

How to replace token in a file using gradle?


In folder where gradle build file is present, I have file named "file" and it has following data :

@tokenval@

In build file I have following thing written :

import org.apache.tools.ant.filters.*
task processResources  {
    filesMatching('file') {
        filter(ReplaceTokens, tokens: [tokenval:  1])
    }
}

I want to replace @tokenval@ in file with 1. But it's giving following error when i run using gradle -q processResources :

A problem occurred evaluating root project 'gradle learning experiments'.
> Could not find method filesMatching() for arguments [file, build_biz3ipxhnv8xkmjuuxur85z50$_run_closure1$_closure2@7d811b8] on task ':processResources' of type org.gradle.api.DefaultTask.

Solution

  • This will copy the input file to the project build/ directory and replace the token in the copy:

    import org.apache.tools.ant.filters.*
    task processResources(type: Copy)  {
        from('file') {
            filter(ReplaceTokens, tokens: [tokenval:  '1'])
        }
        into(buildDir)
    }