简体   繁体   English

groovy + shell:转义字符

[英]groovy + shell : Escaping characters

I am using Jenkins Pipeline using Groovy sandbox. 我正在使用Groovy沙箱使用Jenkins Pipeline。 And i am trying to run a shell script in a groovy sh function. 我正在尝试在groovy sh函数中运行shell脚本。

The original shell script is 原始的shell脚本是

sed -i 's/sometext/'"${othertext}"'/' filename

I am trying to replace a particular text with other text (taken dynamically). 我正在尝试将其他特定文本替换为其他文本(动态获取)。 The script works fine when executed directly. 直接执行脚本时,脚本运行良好。 But I want to use it in jenkins groovy sh function. 但是我想在jenkins groovy sh函数中使用它。

sh(script: '<above shell script>',  returnStdout:false)

But there is a problem of escaping characters. 但是存在转义字符的问题。 I tried this way of escaping character 我尝试过这种转义字符的方式

sh (script: '''sed -i 's/sometext/othertext/' filename''', returnStdout:false)

It works fine but othertext is not taken dynamically. 它工作正常,但不会动态获取其他othertext Can someone please help me in escaping characters with the original script? 有人可以帮我用原始脚本转义字符吗? Or please suggest any other way of doing this. 或者,请提出其他任何建议的方法。

With the inputs from daggett and mkobit and i did few experiments, the following script worked well 利用daggettmkobit的输入,我做了很少的实验,以下脚本运行良好

def l_othertext = sh(script: 'echo ${othertext}', returnStdout: true).trim()
print('l_othertext='+l_othertext)
sh "sed -i 's/sometext/'${l_othertext}'/' filename"

if othertext is a groovy variable then this should work: 如果othertext是一个groovy变量,那么这应该起作用:

def othertext = 'newtext'
sh (script: """sed -i 's/sometext/${othertext}/' filename""", returnStdout:false)
node{
   sh 'sed -i 's/sometext/'"${othertext}"'/' filename'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM