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

PerlRegular Expressions

Avatar of undefined
Last Comment
farzanj
ASKER CERTIFIED SOLUTION
Avatar of jeromee
jeromee
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of farzanj
farzanj
Flag of Canada image

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;        
}
Avatar of farzanj
farzanj
Flag of Canada image

Yes, I believe jeromee got want you wanted.  I thought $file was the file you wanted to open.  Nevermind.
Perl
Perl

Perl is a high-level, general-purpose, interpreted, dynamic programming languages with over 25 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large-scale development projects. Perl gained widespread popularity as a Common Gateway Interface (CGI) scripting language, in part due to its regular expression and string parsing abilities. In addition to CGI, Perl is used for graphics programming, system administration, network programming, finance, bioinformatics, and other applications.

26K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo