jenkins escape sed command

点点圈 提交于 2019-12-12 10:32:46

问题


Can someone escape this sed shell command in Jenkins groovy script for me?

So hard.

sh ("""
sed "s/(AssemblyInformationalVersion\(\")(.*)(\")/\1${productVersion}\3/g" 
AssemblyInfoGlobal/AssemblyInfoGlobal.cs -r
""")

回答1:


The triple-double-quote (""") string literal syntax allows for variable/expression substitution (interpolation), so the backslash (\) is interpreted as a special character "escape". Since the first open paren is not such a special character, Groovy compilation fails. If your intent is to have literal backslashes in the resulting string, you need to escape the backslashes. That is, use a double-backslash (\\) to substitute for one literal backslash.

Thus:

sh ("""
sed "s/(AssemblyInformationalVersion\\(\\")(.*)(\\")/\\1${productVersion}\\3/g" 
AssemblyInfoGlobal/AssemblyInfoGlobal.cs -r
""")



回答2:


So if you like to replace some chars or word in an String groovy variable, for example replacing "/" with "/" in order to escape an special character, which in our case will be the forward slash you can use the code below.

So afterwards we'll be able to apply the linux sed command without getting an error (for instance using sed to replace a place holder value with the desired value in an .env file).

Below we show a Jenkins Pipeline Groovy code:

        String s = "A/B/C"
        your_variable = s.replace("/", "\\/")
        sh "sed -i -e 's/string_to_replace/${your_variable}/g' path/to/file/.env"

NOTE: ${your_variable} will get the content of your variable.

VALIDATION:

echo "Your variable new content: ${your_variable}"

RESULT:

Your variable new content: A\/B\/C


来源:https://stackoverflow.com/questions/40895903/jenkins-escape-sed-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!