Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jenkins escape sed command

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
""")
like image 906
orange Avatar asked Nov 30 '16 18:11

orange


2 Answers

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
""")
like image 88
BalRog Avatar answered Sep 19 '22 19:09

BalRog


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
like image 30
Exequiel Barrirero Avatar answered Sep 22 '22 19:09

Exequiel Barrirero