Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand a shell variable in a Perl command

Tags:

shell

perl

I want to replace the string using a shell variable.

today =`date '+%Y%m%d'`

perl -p -i -e 's/file"20221212"/file="${today}"/g' 

The expectation is file="20221215". But it failed, result is file="".

How to escape this case?

like image 586
92rwf0lXXW4m Avatar asked Dec 01 '25 12:12

92rwf0lXXW4m


1 Answers

Your issue is shell quoting. Using single quotes, ', to delimit the Perl code disables all variable expansion. You need to use double quotes, ", to get variable expansion.

Using shell without any Perl to illustrate the issue

today=`date '+%Y%m%d'`
echo 'today is $today'

will output this -- with no expansion of $today

today is $today

now with double quotes

today=`date '+%Y%m%d'`
echo "today is $today"

outputs this -- $today has been expanded.

today is 20221215

Applying that to your code (I've removed the -i option to make it easier to see the results) and escaped all double quotes in the perl code with \"

echo 'file"20221212"' >input.txt
perl -p  -e "s/file\"20221212\"/file=\"${today}\"/g" input.txt 

gives

file="20221215"
like image 50
pmqs Avatar answered Dec 03 '25 09:12

pmqs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!