Search code examples
groovyreplaceconfig

How to replace value in text file with integer? - Groovy (Qupath)


I want to replace a specific value with an integer in a text value. Seems like I am missing something important.

x=5


def file = new File('/Users/path/name.txt')
def newConfig = file.text.replace('abc',x)
file.text = newConfig

tried x.toString() but did not help either.

I am using this code to generate a number, and need that number to be replaced within a .json file.

Thank you


Solution

  • Let's say we have a file with the following string:

    testabcandanotherabc
    abcandabcandanotherabc
    

    I use the following code:

    x = 5
    def file = new File('/Users/path/name.txt')
    def newConfig = file.text.replaceAll('abc', x.toString())
    file.write(newConfig)
    

    It changes the file content as following:

    test5andanother5
    5and5andanother5
    

    I hope it will help.