The following Perl syntax replaces OLD with NEW, but not if 开发者_开发知识库a digit exists before or after the OLD word.
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
My question:
I also not want to replace the OLD with NEW if a-z or A-Z letters exist before or after OLD word.
Please advise how to change my Perl syntax in order to do that?
Examples (of which OLD word need to replace with NEW):
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
This works for me:
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
!
It's a shell script - I removed the '-i
' option since there isn't a file to overwrite (and I want to see the result).
The original script with the (\b|\D)
constructs were odd; the '\D
' part (non-digit) allows an alphabetic character to precede the match. The change to use just '(\b|[[:^alnum:]])
' twice insists on a word boundary or a non-alphanumeric character. The word boundary matters at the beginning or end of a line. The captures are now needed.
Output
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
精彩评论