Created
January 17, 2023 12:57
-
-
Save vKxni/cb9a9afcbadf7af0242a1b971f0e53a6 to your computer and use it in GitHub Desktop.
Hash files recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Digest::MD5 qw(md5_hex); | |
# Get all files in the current directory | |
opendir(DIR, ".") or die $!; | |
my @files = readdir(DIR); | |
closedir(DIR); | |
# Loop through each file | |
foreach my $file (@files) { | |
# Skip if it's not a regular file or if it already has "[copy]" in the name | |
next if ((-f $file) && ($file !~ m/\[copy\]/)); | |
# Open the original file | |
open(my $fh, "<", $file) or die "Could not open file '$file': $!"; | |
# Read the file's content | |
my $content = do { local $/; <$fh> }; | |
# Hash the content using MD5 | |
my $hashed_content = md5_hex($content); | |
# Close the original file | |
close $fh; | |
# Create the new file name | |
my $new_file = $file; | |
$new_file =~ s/(.*)\.(.*)/$1\[copy\].$2/; | |
# Open the new file for writing | |
open(my $fh2, ">", $new_file) or die "Could not open file '$new_file': $!"; | |
# Write the hashed content to the new file | |
print $fh2 $hashed_content; | |
# Close the new file | |
close $fh2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment