Raj
Raj

Reputation: 887

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

Upvotes: 0

Views: 215

Answers (3)

ikegami
ikegami

Reputation: 385655

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

Upvotes: 3

cdtits
cdtits

Reputation: 1128

Maybe:

s/^A_B_(?!C)/X_Y_/;

or:

s/^A_B_(?!C)/X_Y_/i;

Upvotes: 3

CyberDem0n
CyberDem0n

Reputation: 15036

$line =~ s/^A_B_([^C])/X_Y_$1/;

You should do this for each line of your file.

Upvotes: 1

Related Questions