Groovy regex when replacing tokens in a file
I have a text file with a marker " %%#%
" located all over the inside of it. I'm trying to write a quick and dirty Groovy shell script to replace all instances %%#%
with a dollar sign $
.
So far I have:
#!/usr/bin/env groovy
File f = new File('path/to/my/file.txt')
f.withWriter{ it << f.text.replace("%%#%", "$") }
But when I run this script, nothing happens (no exceptions and no line replacement). I wonder if any of the characters I'm looking for, or the dollar sign itself, are interpreted as a special char by the regex engine under the hood. In any case where I am wrong?
source to share
First I needed to read the contents of the file and then write to the file. Seems to withWriter
erase the contents of the file:
def f = new File('/tmp/file.txt')
text = f.text
f.withWriter { w ->
w << text.replaceAll("(?s)%%#%", /\$/)
}
You might want to do it for each line if the file is too big. Otherwise, you can use this multi-line (?s)
regex .
Note. I chose $
because replace
u replaceAll
behaves differently, in the sense that it replace
accepts char
and thus will not be affected by regex strings, whereas an replaceAll
escape would be required.
Here's my test:
$ echo "%%#%
aaaa
bbbb
cccc%%#%dddd" > file.txt && groovy Subst.groovy && cat file.txt
$
aaaa
bbbb
cccc$dddd
source to share