user3147658
user3147658

Reputation: 21

perl replace time stamp digits inside string

I have a problem using perl to replace timestamp on the fly. Inside config.pm, I have a place holder for timestamp:

our $PrintableTimeStamp = "20130101_010101";

I would like to replace the digits with the current timestamp generated on the fly, i.e.,

$current = $year.$mon.$mday."_".hour.$min.$sec; # (e.g., 20131230_153001)

I used the following command works,

perl -p -i.bak -e s/20130101_010101/$current/g config.pm

but not this one below, which I hope can be more generic and flexible

perl -p -i.bak -e s/\d{8}_\d{6}/$current/g config.pm

Any reason?

Upvotes: 0

Views: 224

Answers (1)

jr0207
jr0207

Reputation: 47

You should consider binding =~ and you probably need to group () your expected string of numbers in your regex pattern. Here's an example of a routine I wrote to verify a MAC address is the correct length before I use it in a database query:

sub verify { #{{{ pull out the colons, verify char = 12, replace colons
my @newmac;
    foreach my $hostmac (@_) {
    chomp($hostmac);
    if ($hostmac =~ /(?:[A-F0-9]{2}:){5}[A-F0-9]{2}/) {
        push (@newmac,$hostmac);
    } else {
        my $count;
        $hostmac =~ s/\://g; # take out the colons
        if ($hostmac =~ /^.{12}$/ ) { # make sure we have a 12 character string
            $hostmac = sprintf "%s:%s:%s:%s:%s:%s", unpack("(A2)6","\U$hostmac\E");
            push (@newmac, $hostmac);
        } else {
            print "$hostmac\n";
            print colored ("$hostmac should be 12 characters long\n", 'red'); die; # You FAIL!!
        }
    }
}
return $newmac[0] if $#newmac == 1;
return @newmac;

}

Upvotes: 1

Related Questions