How to change selected values ​​in a text file using Perl

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

Original file:

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

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

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

Please suggest a solution for this.

+3
source share
2 answers

* edit: it looks like I misunderstood the question a 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);
+2
source

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 is your text file | this.pl to get it on stdout.

+1

Source: https://habr.com/ru/post/1750968/


All Articles