[英]Perl : Selective string substitution
I have a text file which contains strings with prefix A_B_. 我有一个文本文件,其中包含带有前缀A_B_的字符串。
Example: A_B_Monday
示例:
A_B_Monday
I would like to replace all occurences of A_B_*
with X_Y_*
except when * is C
. 我想用
X_Y_*
替换A_B_*
所有出现,除非*是C
So all strings that are A_B_*
but not A_B_C
must be replaced by X_Y_*
. 因此,必须将所有
A_B_*
但不是A_B_C
字符串替换为X_Y_*
。
How should this be done in perl? 在perl中应该怎么做?
Edit:1 The * above is a string. 编辑:1上面的*是一个字符串。 So all A_B_* that are not A_B_Geneva should be replaced with X_Y_NewYork.
因此,所有不是A_B_Geneva的A_B_ *都应替换为X_Y_NewYork。 perl -pi.bak -e 's/^A_B_(!Geneva)/X_Y_/g;'
perl -pi.bak -e's / ^ A_B _(!Geneva)/ X_Y_ / g;' File.Txt does not seem to work.
File.Txt似乎不起作用。 I am on Strawberry Perl.
我在草莓Perl上。
Update: This worked for me perl -i.bak -pE "s/A_B_(?!Geneva)/USB_EP_/g" File.Txt 更新:这对我有用perl -i.bak -pE“ s / A_B _(?! Geneva)/ USB_EP_ / g” File.Txt
Maybe: 也许:
s/^A_B_(?!C)/X_Y_/;
or: 要么:
s/^A_B_(?!C)/X_Y_/i;
s/^A_B_(?!Type\z)/X_Y_/;
Without the \\z
, A_B_Typed
won't get changed to X_Y_Typed
as it should. 没有
\\z
, A_B_Typed
不会像应有的那样更改为X_Y_Typed
。
You could use it as following: 您可以按以下方式使用它:
perl -pi.bak -pe"s/^A_B_(?!Type\z)/X_Y_/g" file
$line =~ s/^A_B_([^C])/X_Y_$1/;
您应该对文件的每一行执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.