以下Perl语法将OLD替换为NEW,但如果OLD字之前或之后存在数字则不会。
OLD=ABBA1 ; export OLD
NEW=OBAMA1 ; export NEW
perl -i -pe 'next if /^ *#/; s/(\b|\D)$ENV{OLD}(\b|\D)/$1$ENV{NEW}$2/g' file
如果在OLD单词之前或之后存在a-z或A-Z字母,我也不想用NEW替换OLD。
请告知如何更改我的Perl语法才能做到这一点?
ABBA1R - not replace
QABBA1 - not replace
ABBA1W - not replace
@ABBA1 - replace ABBA1 with OBAMA1
ABBA1= - replace ABBA1 with OBAMA1
ABBA1w - not replace
4ABBA1 - not replace
ABBA11 - not replace
e ABBA1 - replace ABBA1 with OBAMA1 (remark between e to ABBA1 I have space)
ABBA1 p - replace ABBA1 with OBAMA1 (remark between ABBA1 to p I have space)
?ABBA1 - replace ABBA1 with OBAMA1
_ABBA1_ - replace ABBA1 with OBAMA1
答案 0 :(得分:0)
这对我有用:
OLD=ABBA1 ; export OLD
NEW=OBAMA1 ; export NEW
perl -pe 'next if /^ *#/;
s/(\b|[[:^alnum:]])$ENV{OLD}(\b|[[:^alnum:]])/$1$ENV{NEW}$2/g' <<!
ABBA1R - not replace
QABBA1 - not replace
ABBA1W - not replace
@ABBA1 - replace
ABBA1= - replace
ABBA1w - not replace
4ABBA1 - not replace
ABBA11 - not replace
e ABBA1 - replace (remark between e to ABBA1 I have space)
ABBA1 p - replace (remark between ABBA1 to p I have space)
?ABBA1 - replace
_ABBA1_ - replace
!
这是一个shell脚本 - 我删除了'-i
'选项,因为没有要覆盖的文件(我希望看到结果)。
(\b|\D)
构造的原始脚本很奇怪; '\D
'部分(非数字)允许字母字符在匹配之前。仅使用“(\b|[[:^alnum:]])
”两次的更改会坚持使用单词边界或非字母数字字符。单词边界在一行的开头或结尾处很重要。现在需要捕获。
ABBA1R - not replace
QABBA1 - not replace
ABBA1W - not replace
@OBAMA1 - replace
OBAMA1= - replace
ABBA1w - not replace
4ABBA1 - not replace
ABBA11 - not replace
e OBAMA1 - replace (remark between e to OBAMA1 I have space)
OBAMA1 p - replace (remark between OBAMA1 to p I have space)
?OBAMA1 - replace
_OBAMA1_ - replace