zXi
zXi

Reputation: 112

Replace except for the first occurrence in Perl

I have a file where all the servers are listed as Dominos_A.

Is it possible to change the occurrence of Dominos_A to Dominos_B, Dominos_C except the first match?

FileA:

  ..
  ....
  .....
  Server = Dominos_A.check
  ..
  .
  Server = Dominos_A.check
  Server = Dominos_A.check
  ..
  .
  Server = Dominos_A.check

to

FileA:

  ..
  ....
  .....
  Server = Dominos_A.check
  ..
  .
  Server = Dominos_B.check
  Server = Dominos_C.check
  ..
  .
  Server = Dominos_D.check
  ..

I tried with substr, still i am unable to get the change.

Upvotes: 1

Views: 323

Answers (2)

Vijay
Vijay

Reputation: 67231

@mpapec..Unfortunately this does not work on my solaris box with perl v5.8.4.

So i have written a slightly different one that works for me.

> perl -pe 'BEGIN{@r="A".."Z";$i=0}s/(Dominos_)A/$1$r[$i++]/g' temp
  ..
  ....
  .....
  Server = Dominos_A.check
  ..
  .
  Server = Dominos_B.check
  Server = Dominos_C.check
  ..
  .
  Server = Dominos_D.check
>

Upvotes: 1

mpapec
mpapec

Reputation: 50647

If your last occurrence does not go beyond Z letter, you can

perl -i -pe'
  BEGIN{ @r = "A" .. "Z" }
  s|Dominos_\K\w| shift @r |e;
  # for perl 5.8 or older
  # s|(Dominos_)\w| $1 . shift @r |e; 
' FileA

Upvotes: 4

Related Questions