in reply to Re^19: search and replace strings in different files in a directory
in thread search and replace strings in different files in a directory
Dear Anonymous Monk(s)
Of course, sorry I forgot to post the most recent version of the code.
use 5.014; use strict; use warnings; use Path::Tiny qw/ path /; use POSIX(); use autodie qw/ close /; use File::BOM; use Carp::Always; use Data::Dump qw/ dd /; use Win32; use Win32::Unicode qw/ statW /; Main( @ARGV ); exit( 0 ); sub Main { #my( $infile_paths ) = @_; my( $infile_paths ) = 'C:\dev\test_paths.txt';; my @paths = GetPaths( $infile_paths ); #print "The following paths were in the file:\n"; #say for @paths; for my $path ( @paths ){ RetrieveAndBackupXML( $path ); } #return @paths; } ## end sub Main sub GetPaths { use File::BOM; ## my @paths = path( shift )->lines_utf8; my @paths = path( shift )->lines( { binmode => ":via(File::BOM)" } + ); s/\s+$// for @paths; # "chomp" return @paths; } ## end sub GetPaths sub RetrieveAndBackupXML { #~ my( $directory ) = @_; ## same as shift @_ ## same as shift my $directory = shift; my $date = POSIX::strftime( '%Y-%m-%d', localtime ); #sets cu +rrent date and time to be added to backup file my $bak = "$date.bak"; #date added to the .bak file my @xml_files = path( $directory )->children( qr/\.xml$/ ); for my $file ( @xml_files ) { Replace( $file, "$file-$bak" ); #sub Replace using it's 2 para +meters as defined below } } ## end sub Main sub Replace { my( $in, $bak ) = shift; path( $in )->move( $bak ); #Creates a copy of the original file my $infh = path( $bak )->openr_raw; my $outfh = path( $in )->openrw_raw; while( <$infh> ) { #s{&}{&}g; ## will match more than what you want fix it s{&amp;}{&}g; s{\s>\s}{>}g; s{\s<\s}{<}g; print $outfh $_; } close $infh; close $outfh; } ## end sub Replace
In case you spot an errors in terms of comments, please do comment on the comment(s) in the code, the more feedback the better, since I might be using that code a lot and might also have to explain to colleagues.
Thanks a mil for your help
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^21: search and replace strings in different files in a directory
by Anonymous Monk on Sep 04, 2014 at 10:31 UTC | |
by PitifulProgrammer (Acolyte) on Sep 09, 2014 at 10:23 UTC | |
by PitifulProgrammer (Acolyte) on Sep 09, 2014 at 10:28 UTC | |
by Athanasius (Archbishop) on Sep 10, 2014 at 04:35 UTC | |
by PitifulProgrammer (Acolyte) on Sep 10, 2014 at 11:02 UTC | |
| |
|
Re^21: search and replace strings in different files in a directory
by Anonymous Monk on Sep 04, 2014 at 09:19 UTC |