Five Things You Didn't Know You Could Do with Perl - ' Archiving Files ' (
Page 3 of 6 )
Archiving Files Intelligently
Frequently, I find myself building up a tar file based on some very specific conditions. For example, I want to create an archive based on files that have only changed since a specific date and time. Specifying this time can be difficult, so it's use to to use the time of another file. I also use CVS to manage my projects, but I don't always want to include the CVS information in my archive.
Therefore, I created the following script. It combines the Archive::Tar module, which creates Tar archives, and the output from the find2perl script, which generates a Perl version of a Unix find command. I've then modified it slightly to extend the functionality a little to suit my needs.
ADVERTISEMENT
The flexibility of Perl means I could just have easily created a Zip, or modified the find function to select and specify a different selection from the files it finds.
use strict;
use Archive::Tar;
use File::Find;
my ($min,$hour,$day,$mon,$year) = (localtime())[1..5];
$mon++;
$year += 1900;
unless (@ARGV >= 3)
{
print <<EOF;
Usage: $0 basename compare directories...
where basename is prefixed to the current date and time
compare is the name of the file you want to use as
the modification time reference
EOF
exit(1);
}
my $base = shift;
my $compare = shift;
my $compare_time = (stat($compare))[9];
open(FILE,">$compare") or die "Can't update comparison file, $compare\n";
print FILE $compare_time;
close(FILE);
my @filelist;
find(\&wanted,@ARGV);
if (@filelist)
{
my $arcname = sprintf("%s.%04d%02d%02d.%02d%02d.tar.gz",
$base,$year,$mon,$day,$hour,$min);
print("Writing ",scalar @filelist," files to $arcname\n");
my $archive = Archive::Tar->new();
$archive->add_files(@filelist);
$archive->write($arcname,1);
}
exit;
sub wanted
{
my $full = $File::Find::name;
return unless(-f $_);
return if (/^\./ or /~$/ or /^\#.*\#$/ or $full =~ /CVS/);
my $mtime = (stat($_))[9];
return unless ($mtime > $compare_time);
print "Adding $full to archive\n";
push @filelist,$full;
}
To create a new archive, type:
$ archive.pl update .lastarchive .
The file automatically has the date and time embedded into the name, making it easy to identify when the archive was generated.