使用REGEX和Groovy和SED替换值

时间:2022-01-12 16:48:16

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

我有一个包含“描述”属性的XML文件。我想用不同的描述替换该属性的内容。我在Groovy脚本中使用SED命令

<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".

我尝试了以下行,但它没有用字符串“bar”替换“Description”值的值。

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

更新:根据下面的WiktorStribiżew的评论,我更新了命令以反映最新的错误

1 个解决方案

#1


1  

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:

您使用带有BRE正则表达式的sed(即没有-E或-r选项),因此您的(和)被解析为文字括号,而不是分组构造。无论如何,你没有使用反向引用并替换整个匹配,没有必要保留括号:

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?

如果需要使用变量,请参阅如何在sed命令中使用变量?

The sed command will look as

sed命令看起来像

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

See this demo.

看这个演示。

#1


1  

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:

您使用带有BRE正则表达式的sed(即没有-E或-r选项),因此您的(和)被解析为文字括号,而不是分组构造。无论如何,你没有使用反向引用并替换整个匹配,没有必要保留括号:

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?

如果需要使用变量,请参阅如何在sed命令中使用变量?

The sed command will look as

sed命令看起来像

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

See this demo.

看这个演示。