Skip to content

Instantly share code, notes, and snippets.

@f99aq8ove
Created January 4, 2014 22:47
Show Gist options
  • Save f99aq8ove/8261807 to your computer and use it in GitHub Desktop.
Save f99aq8ove/8261807 to your computer and use it in GitHub Desktop.
Rename NFD directory/file name to NFC directory/file name recursively.
#!/usr/bin/perl
use strict;
use warnings;
use encoding 'utf-8';
use Unicode::Normalize;
use File::Basename qw/fileparse/;
use Getopt::Long;
my $noexecute = 0;
GetOptions('n' => \$noexecute,);
my $topDir = shift;
my $walk;
$walk = sub {
my $dir = shift;
opendir my $dh, $dir or die $!;
my @f = map { $dir . '/' . $_ } grep !/^\./, readdir($dh);
closedir $dh;
my @res = @f;
for (@f) {
if (-d $_) {
my @subRes = &$walk($_);
push @res, @subRes;
}
}
@res;
};
my @files = &$walk($topDir);
@files = reverse grep { NFCFilename($_) ne $_ } @files;
if ($noexecute) {
print "$_\n" for map { sprintf "%s\t-> %s", $_, NFCFilename($_) } @files;
}
else {
for my $old (@files) {
my $new = NFCFilename($old);
printf "%s\t-> %s\n", $old, $new;
if (-e $new) {
warn "$new already exists!";
next;
}
rename $old, $new or die $!;
}
}
sub NFCFilename {
my $path = shift;
my ($basename, $dirname) = fileparse $path;
sprintf '%s%s', $dirname, NFC($basename);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment