在Shell脚本中进行Perl搜索和替换

问题描述 投票:0回答:1

我一直在尝试使用Shell脚本和Perl替换.txt文件中的某些文本。

oldKey=123
trimmedNewKey=456

#Export shell variables, so that they can be used by perl
export oldKey
export trimmedNewKey

#Search and Replace
perl -pi -e 's/$ENV{oldKey}/$ENV{trimmedNewKey}/g' AppConstants.txt

这会失败,但是,另一方面,如果我直接将字符串用作搜索参数,则它会起作用:

perl -pi -e 's/123/$ENV{trimmedNewKey}/g' AppConstants.txt.

我不是一个有经验的家伙,无法弄清楚为什么我的“搜索”参数无法通过变量求值。帮助!

bash shell perl
1个回答
0
投票

尝试将您的代码更改为

oldKey=123
trimmedNewKey=456
perl -pi -e "s/$oldKey/$trimmedNewKey/g" AppConstants.txt

这应该起作用,因为在用单引号引起来的字符串中没有变量和通配符扩展,因为在用双引号引起来的字符串中就是这种情况。

也许可以将一些变量传递给perl,以便在perl程序内部进行扩展,但是当您可以通过更简单的方式解决它时,为什么使其变得复杂?

© www.soinside.com 2019 - 2024. All rights reserved.