用Groovy和SED命令替换带有变量的字符串 [英] Replacing string with variable with Groovy and SED command

查看:358
本文介绍了用Groovy和SED命令替换带有变量的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图替换XML文件中包含的整个描述字符串。我想用一个变量替换该字符串。我在Groovy脚本中使用了SED命令。



我有以下代码。我期待字符串富来替换描述文本,但它没有。
取而代之的是,下面的代码行导致XML更改为:
Description =sDescription



我在做什么错误?

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


<在Groovy中,变量/表达式替换内部的字符串(插值)仅适用于特定类型的字符串文本语法。单引号语法('content)

)不是其中之一,但如果用双引号(content)替换外部单引号,则应该获得你要找的插值效果:

  def sDescription =foo
def sedCommand =sed -i's / Description = \[^ \] * \/ Description = \$ sDescription \/ g \'package.appxmanifestas String

这会给你一个包含你想运行的命令的字符串。请注意我是如何更改字符串内特殊字符转义( \ )以反映字符串分隔符中的更改的。



< 正如@tim_yates所指出的那样,为什么当Groovy包含内置于语言中的优秀XML操作工具时,您为什么要调用一个单独的 ad hoc 进程来执行此替换?


I am trying to replace an entire description string contained in an XML file. I would like to replace that string with a variable. I am using a SED command within a Groovy script.

I have the following code. I am expecting the string "foo" to replace the description text but it doesn't. Instead the following line causes the XML to change to: Description="sDescription"

What am I doing wrong?

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

解决方案

In Groovy variable/expression substitution inside of strings (interpolation) only works with certain types of string literal syntax. Single quote syntax ('content') is not one of them. However, if you replace the outer single quotes with double quotes ("content") then you should get the interpolation effect you are looking for:

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

This should give you the string that contains the command you wish to run. Please note how I changed the special character escaping (\) within the string to reflect the change in string delimiters.

Aside: As noted by @tim_yates, Why would you want to invoke a separate ad hoc process to do this substitution when Groovy contains excellent XML manipulation facilities built into the language?

这篇关于用Groovy和SED命令替换带有变量的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆