atb atb - 5 months ago 12
Perl Question

Using a bash variable in regex replace

replace="bar"
echo foo123 | perl -p -e 's/(\d+)/${replace}456/'


Is there a way to use a pre-defined variable in your replacement string? Maybe even a better alternative to
perl
?

Answer
replace="bar"  
echo foo123 | perl -p -e 's/(\d+)/$ENV{replace}456/'

This grabs the shell variable from the environment in which Perl runs. In some circumstances you might need to export first:

export replace="bar"
Comments