Link to home
Start Free TrialLog in
Avatar of KGNickl
KGNicklFlag for United States of America

asked on

Perl Regular Expression To replace value in text of variable?

See the code below. Basically have a file name, a search value, and a replace value. Everything works, but I don't know regular expressions and how to write one where I have the questions marks that will replace take $file and replace the $search_value within it (if found) with the $replace_value.

Not sure if this can be done in one line w/ a regular expression or if there is another easier way? Thanks! Let me know if anything needs clarification.
my $file = "Test_12354a-bc.doc";
    my $search_value = "12354a";
    my $replace_value = "replaced";
        
        if($search_value =~ /\b$file\b/){
            #True, replace $search_value found in $file with the $replace_value
            $file = ?????;
            #$file should now be equal to "Test_replaced-bc.doc"
        }else{
            #False, do nothing
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jeromee
jeromee
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of farzanj
I have code similar to your logic


my $file = "Test_12354a-bc.doc";
my $search_value = "12354a";
my $replace_value = "replaced";

open INFILE, $file or die "$!";
my @lines = <INFILE>;
close INFILE;

foreach my $line (@lines)
{
      $line =~ s/\b$search_value\b/$replace_value/g;        
}
Yes, I believe jeromee got want you wanted.  I thought $file was the file you wanted to open.  Nevermind.