tags:

views:

64

answers:

2

I need help to write some Perl code to replace some selected values in text files. Below is the sample of my text files. I want to replace the value of "end" to a new value in the date format YYYYMMDD, increase the key value by 1, and the rest should remain the same.

Source File:

    server=host1
    network=eth0
    start=YYYYMMDD
    end=YYYYMMDD
    key=34

If I change the "end" value to yyyymmdd (new date) and "key" to +1. the output result should be:

    server=host1
    network=eth0
    start=YYYYMMDD
    end=yyyymmdd
    key=35

Please suggest a solution for this.

+1  A: 

How about this:

#!/usr/bin/env perl

while (<>) {
    s/^end=/WHATEVER=/gi;
    if (/^key=/) {
        ($key,$val) = split("=");
        $val = $val + 1;
        $_ = "$key=$val";
    }
    print;
}

On unix, cat your text file | this.pl to get it on stdout.

jskaggz
Thanks Jskaggz: It works for me but "end" is changed by "WHATEVER". I want to change the value of "end" to the new value I pass. Thanks.
Space
Sure, I would wrap the s/^end=/WHATEVER/g part in a function, and use s/^end=/$whatevervar/g;
jskaggz
A: 

*edit: looks like I misread the question new solution:

#!/usr/bin/perl
$filename = "a.txt";
$tempfile = "b.txt";
$newdate = "whatever";

open(IS, $filename);
open(OS, ">$tempfile");
while(<IS>)
{
    if($_ =~ /^end=(.*)$/){
        print OS "end=$newdate\n";
    } elsif ($_ =~ /^key=(.*)$/) {
        print OS "key=".($1+1)."\n";
    } else {
        print OS $_;
    }
}
close(IS);
close(OS);
unlink($filename);
rename($tempfile, $filename);
proto-n