'awk script inside jenkins pipeline

I am trying to execute below script inside jenkinsfile

awk 'NR==FNR{new=new $0 ORS; next} /^}]$/{printf "}],\n%s", new} 1' output2 ${WORKSPACE}/${REPO}/file1 >> output2

This script works fine in linux command promt but it gives error when tried to run inside jenkins file.I tried below

sh """
   awk 'NR==FNR{new=new $0 ORS; next} /^}]$/{printf "}],\n%s", new} 1' output2 ${WORKSPACE}/${REPO}/file1 >> output2
"""

But it gives syntax error



Solution 1:[1]

You need to watch out for escaping single or double quotes, backslashes and dollar signs. Here I've escaped everything:

sh """
   awk \'NR==FNR{new=new \$0 ORS; next} /^}]\$/{printf \"}],\\n%s\", new} 1\' output2 \${WORKSPACE}/\${REPO}/file1 >> output2
"""

Maybe you actually don't want to escape ${WORKSPACE} or ${REPO} if those are pipeline environment variables that you want substituted by groovy as opposed to by sh. And maybe you don't need to escape the single quotes inside a triple """ multistring. But you definitely need to escape the double quotes and the backslash in \\n.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 david_beauchamp