Friday, April 15, 2022

[SOLVED] perl replace with bash variable

Issue

could someone please explain, why perl doesn't replace the regexp:

root@machine08:~# VERSIONK8S='${VERSION_KUBERNETES:-1.23.3-00}'
# with sed as i want it
root@machine08:~# sed -e "s/^VERSIONK8S=.*/VERSIONK8S=${VERSIONK8S}/g" /root/coding/k8s-setup/allnodes_basic_setup.sh | grep ^VERSIONK8S=
VERSIONK8S=${VERSION_KUBERNETES:-1.23.3-00}
# with perl not exactly as i want it
root@machine08:~# perl -pe "s/^VERSIONK8S=.*/VERSIONK8S=${VERSIONK8S}/g" /root/coding/k8s-setup/allnodes_basic_setup.sh | grep ^VERSIONK8S=
VERSIONK8S=-e

Solution

From Perldoc:

If the delimiter chosen is a single quote, no variable interpolation is done on either the PATTERN or the REPLACEMENT. Otherwise, if the PATTERN contains a $ that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at run-time.

Perl tries to expand the substitution string ${VERSION_KUBERNETES:-1.23.3-00} as a perl variable starting with $ and fails. To avoid the expansion, please try:

perl -pe "s'^VERSIONK8S=.*'VERSIONK8S=${VERSIONK8S}'g" /root/coding/k8s-setup/allnodes_basic_setup.sh | grep ^VERSIONK8S=

by using a single quote as a delimiter instead of a slash such as s'pattern'replacement'.



Answered By - tshiono
Answer Checked By - Cary Denson (WPSolving Admin)