Home > Mobile >  Replace all matches EXCEPT first match in multiple files with perl
Replace all matches EXCEPT first match in multiple files with perl

Time:12-02

I need to do a find/replace in multiple files but I want to keep the first occurrence of the match and replace all others. THis may have been answered else where but it's a bit difficult to search for.

I am currently using: perl -pi -w -e 's/THING/SOMETHING_ELSE/g;' ./src/**/*.py

A practical example:

from stuff import THING

print(f"use {THING} here")
print(f"use {THING} there")
print(f"use {THING} everywhere")

Should become:

from stuff import THING

print(f"use {SOMETHING_ELSE} here")
print(f"use {SOMETHING_ELSE} there")
print(f"use {SOMETHING_ELSE} everywhere")

CodePudding user response:

You'll have to check for /THING/ before doing the s/THING/.../.

Here's how would be as a script thing-to-other that you can then call as thing-to-other ./src/**/*.py

#!/bin/env perl -i -p

if ( /THING/ ) {
    if ( $seen{$ARGV}   ) {
        s/THING/SOMETHING_ELSE/g;
    }
}

Note that I got rid of the -w because the use of the %seen hash will throw a warning. The %seen hash keeps track how many times in each input file ($ARGV) you've seen /MATCH/.

If you really need it to be a one-liner:

perl -i -p -e'if (/THING/) {if($seen{$ARGV}  ){s/THING/SOMETHING_ELSE/g}}'
  •  Tags:  
  • perl
  • Related