kanishka
kanishka

Reputation: 166

Replacing in Perl

So i have a scenario where i have strings like:

TERMS of use    [ER]
SERVICE manager ER Data
Stack OVERFLOW  (ER) check
ERPS Value         ER
GDPER   checks ER

These are the strings where you can see space , multi space or tab between the strings. i want to replace 'ER' with 'GD'.

So i used on command prompt:

perl -n -e 's/[[,(]?ER[),]]?/GD/g&&print';

Input: GDPER checks ER

Output: GDPGD checks GD

Required: GDPER checks GD'

Upvotes: 0

Views: 85

Answers (2)

Stefan Becker
Stefan Becker

Reputation: 5952

Does this work for you?

NOTE: \K requires Perl >= 5.10.0.

$ perl -pe 's/(?:\b|[[:upper:]]*[[:lower:]]+\w*\K)ER\b/GD/g'

Input (copy & paste)

TERMS of use    [ER]
SERVICE manager ER Data
Stack OVERFLOW  (ER) check
ERPS Value         ER
GDPER   checks ER
ThisTestCaseDoesNotReplaceER

Output

TERMS of use    [GD]
SERVICE manager GD Data
Stack OVERFLOW  (GD) check
ERPS Value         GD
GDPER   checks GD
ThisTestCaseDoesNotReplaceGD

Upvotes: 2

stack0114106
stack0114106

Reputation: 8711

Another Perl using positive lookbehind

$ perl -pe 's/(?<=\[|\s|\()ER/GD/g' kanishka.txt
TERMS of use    [GD]
SERVICE manager GD Data
Stack OVERFLOW  (GD) check
ERPS Value         GD
GDPER   checks GD

$

with one more edge case as mentioned by OP in the comments

$ perl -pe 's/(?<=\[|\s|\(|[a-z])ER/GD/g' kanishka.txt2
TERMS of use    [GD]
SERVICE manager GD Data
Stack OVERFLOW  (GD) check
ERPS Value         GD
GDPER   checks GD
ThisTestCaseDoesNotReplaceGD


$ cat kanishka.txt2
TERMS of use    [ER]
SERVICE manager ER Data
Stack OVERFLOW  (ER) check
ERPS Value         ER
GDPER   checks ER
ThisTestCaseDoesNotReplaceER


$

Upvotes: 0

Related Questions