jaxim jaxim - 7 days ago 5
Bash Question

Replace value using REGEX with Groovy and SED

I have an XML file that contains a "Description" property. I would like to replace the contents of that property with a different description. I am using a SED command within a Groovy script

<VisualElements Description="foo" Title="title"/>


I tried the following line, but it does not replace the value of the "Description" value with the string "bar".

def sedCommand = 'sed -i \'s/Description="([^"]*)"/Description="bar"/g\' package.appxmanifest' as String


Can someone tell me what is wrong with the above line?

Update: based on Wiktor Stribiżew's comment below, I have updated the command to reflect the latest error

Answer

You are using sed with a BRE regex (i.e. no -E or -r options), so your ( and ) are parsed as literal parentheses, not a grouping construct. Anyway, you are not using backreferences and replacing the whole match, there is no point keeping the parentheses at all:

def sedCommand = 'sed -i \'s/Description="[^"]*"/Description="bar"/g\'  package.appxmanifest' as String
                                          ^^^^^

will work well.

If you need to use variables, see How do I use variables in a sed command?

The sed command will look as

#!/bin/bash
foo="hello"
echo '<VisualElements Description="foo" Title="title"/>' | \
 sed 's/Description="[^"]*"/Description="'$foo'"/g'

See this demo.