Maire has asked for the wisdom of the Perl Monks concerning the following question:
Good morning Monks,
I have a large folder of text files, and I want to substitute all instances of a certain string within those files with another string (essentially every time the word “end” appears, I want to start a new line).
To do this, I thought it would be safer to use a script that copies the files to a new folder before it modified them. After a bit of Googling, I found a Perl script (created by durden_tyler and uploaded to https://www.unix.com/302318333-post5.html) which, with a couple of modifications, allows me to do just this.
#!perl -w # Script to process all *.txt files in current directory and put the o +utput # in the corresponding *.txt.new files in the current directory again. my $indir = 'C:\Users\li\test'; # the input directory name my $outdir = 'C:\Users\li\test2'; # the output directory name my $i = 0; # loop index my $infile; # the input file name my $outfile; # the output file name while (defined($infile = glob($indir."\\*.txt"))) { # loop + through the txt files in directory $indir printf("(%d)\tNow processing file => %s\t",++$i,$infile); $outfile = $outdir."\\".substr($infile,rindex($infile,"\\")+1); # n +ame the output file open (IFILE, "<$infile") or die "Can't open $infile: $!"; # open + input file for reading open (OFILE, ">$outfile") or die "Can't create file: $!"; # crea +te output file for writing while (<IFILE>) { # loop through contents of the input file my @lines = <IFILE>; my @newlines; foreach(@lines) { $_ =~ s/<\/end>/<\/end>\n/g; push(@newlines,$_); print OFILE $_; } close(IFILE) or die "Can't close $infile: $!"; # clos +e input file close(OFILE) or die "Can't close $outfile: $!"; # clos +e output file printf("Output file => %s\n",$outfile); } }
The only problem is that this process (obviously) alters the original “date modified” Windows timestamps (that are displayed in File Explorer) for the files. This is unfortunate because the timestamps, at the moment, are one of the key ways that I’m keeping track of the large amount of data I’ve got.
Is there any way that I can still substitute the string within each file without losing the original date modified timestamp?
Thanks a lot!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Maintaining date modified timestamp when copying files (updated x2)
by haukex (Archbishop) on Oct 29, 2017 at 09:48 UTC | |
by Maire (Scribe) on Oct 31, 2017 at 09:16 UTC | |
|
Re: Maintaining date modified timestamp when copying files
by Laurent_R (Canon) on Oct 29, 2017 at 11:32 UTC | |
by Anonymous Monk on Oct 29, 2017 at 11:41 UTC | |
by Maire (Scribe) on Oct 31, 2017 at 09:23 UTC | |
by Maire (Scribe) on Oct 31, 2017 at 09:22 UTC |