简体   繁体   中英

Perl find and replace one liner

I've been looking at the other find and replace questions on Perl, and I'm not sure how exactly to implement this variation in one line. The only difference is that I want to replace two things, one is the original, and one is the replacing a modification of the original string. The code I have in a pm module is:

my $num_args = $#ARGV + 1;
if ($num_args != 2) {
    print "\nUsage: pscript.pm path to file [VERSION]\n";
    exit;
}

my $version = $ARGV[1];
my $revision = $ARGV[1];
$revision =~ s/.*\.//g;
open ($inHandle, "<", $ARGV[0]) or die $^E;
open ($outHandle, ">", "$ARGV[0].mod") or die $^E;
while(my $line = <$inHandle>)
{
        $line =~ s/\<Foo\>(.*)\<\/Foo\>/\<Foo\>$version\<\/Foo\>/;
        $line =~ s/\<Bar\>(.*)\<\/Bar\>/\<Bar\>$revision\<\/Bar\>/;
        print $outHandle $line;
}

close $inHandle;
close $outHandle;

unlink $ARGV[0];
rename "$ARGV[0].mod", $ARGV[0];

What is different is:

$revision =~ s/.*\.//g;

which turns the version XXX1000 into just 1000, and then uses that for the find and replace.

Can this be done using the

perl -i.bak  -p -e 's/old/new/g;' *.config

format?

尝试这个 :

perl -i.bak -pe 's/\d+\.\d+\.\d+\.1000\b/1000/g' *.config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM