问题
Is there any way to write a Perl script to calculate the MD5sum of every file in a directory?
If so, how could I do this?
回答1:
Well there are many ways to do this but it comes down to two operations you need to preform. You will first need to locate a list of the files you would like to run the check and then you will need to run the md5sum check on each of those files. There is a ton of ways to do this but the following should work for your needs.
#!/usr/bin/perl
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
my $dirname = "/home/mgreen/testing/";
opendir( DIR, $dirname );
my @files = sort ( grep { !/^\.|\.\.}$/ } readdir(DIR) );
closedir(DIR);
print "@files\n";
foreach my $file (@files) {
if ( -d $file || !-r $file ) { next; }
open( my $FILE, $file );
binmode($FILE);
print Digest::MD5->new->addfile($FILE)->hexdigest, " $file\n";
close($FILE);
}
The above will grab the md5sum for each file in the directory and skip any sub-directories and print it to STDOUT. The MD5 checksum part is then done by the Digest::MD5 module which is ultimately what I think you are looking for.
I do like your question though as it is open-ended with alot of possible solutions like all "How do I do this in perl?" questions so I am sure you will get alot of possible solutions and I will most likely update mine when I get home later.
回答2:
Maybe using find
with -exec
can do the job?
find . -name "*.*" -exec md5sum '{}' \;
The '{}' will be replaced with the name of each file.
回答3:
Use opendir
and readdir
or other recursive method
.
Here is an example:
#!/usr/bin/perl -w
use warnings;
my $DIR_PATH="a";
opendir DIR, ${DIR_PATH} or die "Can not open \"$DIR_PATH\"\n";
@filelist = readdir DIR;
foreach $file (@filelist) {
open(IN,"a/$file")or die "cannot open";
while(<IN>){...}
close IN;
}
来源:https://stackoverflow.com/questions/19460944/how-could-i-write-a-perl-script-to-calculate-the-md5-sum-of-every-file-in-a-dire