in reply to Re: replace all but first
in thread replace all but first

This is what i am trying to do

my text file has
<cnt>Germany</cnt><cmp>ALLIANZ INSURANCE</cmp>
<cnt>Germany</cnt><cmp>ALLIANZ PARKWAY</cmp>
<cnt>Germany</cnt><cmp>ALLIED DOMECQ</cmp>

i want to replace it as
<cnt>Germany</cnt><cmp>ALLIANZ INSURANCE</cmp>
<TAB><cmp>ALLIANZ PARKWAY</cmp>
<TAB><cmp>ALLIED DOMECQ</cmp>

i.e. i want to replace "<cnt>Germany</cnt>" to "<TAB>" from its second occurance

Replies are listed 'Best First'.
Re^3: replace all but first
by Not_a_Number (Prior) on Sep 03, 2004 at 14:35 UTC
    use strict; use warnings; my %seen; while ( <DATA> ) { next unless /^(<cnt>([^<]+)<\/cnt>)(.*)$/; print $seen{$2}++ ? "<TAB>$3\n" : "$1$3\n"; } __DATA__ <cnt>France</cnt><cmp>ACCOR</cmp> <cnt>France</cnt><cmp>AGF</cmp> <cnt>France</cnt><cmp>AIR LIQUIDE</cmp> <cnt>Germany</cnt><cmp>ALLIANZ INSURANCE</cmp> <cnt>Germany</cnt><cmp>ALLIANZ PARKWAY</cmp> <cnt>Germany</cnt><cmp>ALLIED DOMECQ</cmp> <cnt>United Kingdom</cnt><cmp>LEICESTER CITY FOOTBALL CLUB</cmp> <cnt>United Kingdom</cnt><cmp>SPENCER GEARS</cmp>
Re^3: replace all but first
by Roy Johnson (Monsignor) on Sep 03, 2004 at 14:41 UTC
    If it's not going to appear twice on the same line:
    my $seen=0; while(<DATA>) { if ($seen) { s{<cnt>Germany</cnt>}{<TAB>} } else { $seen ||= m{<cnt>Germany</cnt>} } print; } __DATA__ <cnt>Germany</cnt><cmp>ALLIANZ INSURANCE</cmp> <cnt>Germany</cnt><cmp>ALLIANZ PARKWAY</cmp> <cnt>Germany</cnt><cmp>ALLIED DOMECQ</cmp>

    Caution: Contents may have been coded under pressure.
Re^3: replace all but first
by EdwardG (Vicar) on Sep 03, 2004 at 15:02 UTC
    $data =~ s{(<cnt>Germany</cnt>)}{$seen++?'<TAB>':$1}ge;