in reply to Print text on the same line after match
I usually create a new file with its new name rather than renaming the original file and I compare new and old to make sure nothing has gone wrong before unlinking the original. Perhaps an over-complication but a background in systems administration, where trashing a file could bring down a service, has instilled caution.
use strict; use warnings; use POSIX qw{ strftime }; use Digest::MD5; my $origFile = q{cr835.txt}; open my $origFH, q{<}, $origFile or die qq{open: < $origFile: $!\n}; my $line = <$origFH>; close $origFH or die qq{close: < $origFile: $!\n}; my $payeeID; if ( $line =~ m{INC\*XX\*(\d+)} ) { $payeeID = $1; } else { die qq{Could not match payee ID\n}; } my $newFile = qq{cr835-} . $payeeID . strftime q{-processed_%Y-%m-%d_%H-%M.txt}, localtime; open my $newFH, q{>}, $newFile or die qq{open: > $newFile: $!\n}; print $newFH $line; close $newFH or die qq{close: > $newFile: $!\n}; my $origMD5 = Digest::MD5 ->new() ->addfile( do { open my $fh, q{<}, $origFile or die $!; $fh; } ) ->hexdigest(); my $newMD5 = Digest::MD5 ->new() ->addfile( do { open my $fh, q{<}, $newFile or die $!; $fh; } ) ->hexdigest(); if ( $origMD5 eq $newMD5 ) { unlink $origFile or die qq{unlink: $origFile: $!\n}; } else { die qq{Original and new files differ\n}; }
I hope this is helpful.
Cheers,
JohnGG
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Print text on the same line after match
by BillKSmith (Monsignor) on Dec 15, 2018 at 03:48 UTC | |
by johngg (Canon) on Dec 15, 2018 at 14:24 UTC |