Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy regex when replacing tokens in file

I have a text file that has the token "%%#%" located all over the place inside of it. I am trying to write a quick-and-dirty Groovy shell script to replace all instances of "%%#%" 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 string replacement). I wonder if any of the characters I'm searching for, or the dollar sign itself, is being interpreted as a special char by the regex engine under the hood. In any event, Where am I going awry?

like image 378
Venkat Avatar asked Oct 01 '22 02:10

Venkat


1 Answers

I had to read the file content first, and then write on the file. Seems like withWriter erases the file contents:

def f = new File('/tmp/file.txt')
text = f.text
f.withWriter { w ->
  w << text.replaceAll("(?s)%%#%", /\$/)
}

You might want to do a per line read if the file is too large. Otherwise, you can use that multiline (?s) regex.

Note I escaped $, because replace and replaceAll behaves differently, in a sense that replace accepts a char and, thus, will be unaffected by regex strings, whereas replaceAll will need escaping.

Here is my test:

$ echo "%%#%
aaaa
bbbb
cccc%%#%dddd" > file.txt && groovy Subst.groovy && cat file.txt 
$
aaaa
bbbb
cccc$dddd
like image 166
Will Avatar answered Oct 10 '22 01:10

Will