Multiple search and replace app?



  • Hi all,
    I have a simple need for which I have not been able to find any prebuilt solutions (yes I know I could sit down and code a custom app - but I am surprised that I might have to, and if I do it is not going to count as billable time). It maybe that I am looking in the wrong places, but a fair bit of googling has not turned up anything decent.

    In its simplified form I need to take a text file like: "AAA BBB CCC" and a list of changes "AAA->BBB", "BBB->CCC" and "CCC->AAA", apply them to the file and end up with "BBB CCC AAA". There are heaps of solutions on the net that all promise multiple search and replace, but it seems that that ones I have tested today all fall into the trap of assuming that the replacement text from one rule will not trigger the firing of another rule. This WTF results in the following steps:

    From "AAA BBB CCC", apply "AAA->BBB" which results in "BBB BBB CCC".

    Apply "BBB->CCC" which results in "CCC CCC CCC".

    Apply "CCC->AAA" which results in "AAA AAA AAA"

    So does anyone have a fav app that would successfully apply the changes without side effects? I am looking for a windows solution that will allow for an arbitrary number of changes which are specified in an external file. The ability to run the change set over multiple files would be nice but not necessary, and multiple dirs is not a requirement.

    Thanks.



  • Sounds like diff and patch.



  • I can't see that approach working. Diff takes two files and produces the difference. I won't have the second file until after I apply the changes.



  • @OzPeter said:

    I won't have the second file until after I apply the changes.

    Throw cp into the mix



  •  I believe MySQL includes a replace program that does, but it's probably overkill to install MySQL for that one program.  And I'm not sure if the Windows version even has that program.  So, in short, I'm really no use at all.



  • It's not hard to do this with a sed or Perl script, if you do it in two stages. First, replace each target string with a placeholder that's guaranteed not to appear in the text. Next, replace the placeholders with the final strings. This'd make a good Perl Golf challenge, actually.

    Something like this:

    use strict;
    

    my %reps = ( "AAA"=>"BBB","BBB"=>"CCC", "CCC"=>"AAA" );
    my @targets = keys %reps;

    print @targets;

    while(<>) {
    my $x;
    for ($x=0; $x < @targets ; $x++)
    {
    my $what = $targets[$x];
    s/$what/PLACEHOLDER$x/g;
    }
    # print $;
    for ($x=0; $x < @targets ; $x++)
    {
    my $what=$reps{$targets[$x]};
    s/PLACEHOLDER$x/$what/g;
    }
    print $
    ;
    }

     



  • @mbessey said:

    It's not hard to do this with a sed or Perl script, if you do it in two stages.

    After seeing that I sorta went D'oh (its been a long week). But I am still amazed that all these apps out there don't do a 2 stage substitutions


Log in to reply