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
""")
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
""")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With