shell - 如何在 Perl 命令中扩展 shell 变量

标签 shell perl

我想使用 shell 变量替换字符串。

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

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

预期是 file="20221215"。 但是它失败了,结果是 file=""

如何逃脱这种情况?

最佳答案

您的问题是 shell 引用。使用单引号,' , 分隔 Perl 代码禁用所有变量扩展。您需要使用双引号," , 得到变量展开。

使用没有任何 Perl 的 shell 来说明问题

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

将输出这个 -- 没有 $today 的扩展

today is $today

现在用双引号

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

输出这个 -- $today已扩展。

today is 20221215

将其应用于您的代码(我删除了 -i 选项以便更容易查看结果)并使用 \" 转义了 perl 代码中的所有双引号

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

给予

file="20221215"

关于shell - 如何在 Perl 命令中扩展 shell 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74808644/

相关文章:

shell - Emacs shell : outlining input, 输出,错误

linux - Bash 使用两个列表创建目录/子目录

linux - Hash ("#") symbol in/etc/environment 导致字符串被拆分

perl - %ENV不起作用,我无法使用共享库

Perl : CRTL C ignored when calling subroutine instead of exiting

linux - 如何处理ssh key ?

linux - 将长单行命令转换为 bash shell 脚本

sql - 为什么我的 Perl CGI 脚本找不到 Oracle DBD?

perl - 如何让 2 个版本的 perl 在 Windows 7 上运行?

python - 新数据库和 Django manage.py shell 和 syncdb 没有运行