简体   繁体   中英

Perl : Selective string substitution

I have a text file which contains strings with prefix A_B_.

Example: A_B_Monday

I would like to replace all occurences of A_B_* with X_Y_* except when * is C .

So all strings that are A_B_* but not A_B_C must be replaced by X_Y_* .

How should this be done in perl?

Edit:1 The * above is a string. So all A_B_* that are not A_B_Geneva should be replaced with X_Y_NewYork. perl -pi.bak -e 's/^A_B_(!Geneva)/X_Y_/g;' File.Txt does not seem to work. I am on Strawberry Perl.

Update: This worked for me 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.

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/;

您应该对文件的每一行执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM