Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Created April 6, 2020 16:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elfsternberg/79ea4c00f34500cfe6307b64fb2ee209 to your computer and use it in GitHub Desktop.
Save elfsternberg/79ea4c00f34500cfe6307b64fb2ee209 to your computer and use it in GitHub Desktop.
A simple perl script to enable bulk renaming of files.
#!/usr/bin/env perl
# RN
#
# `rn` is a bulk renaming script for the Linux filesystem. It takes a
# single transformation argument followed by a list of filenames. The
# transformation argument must be a perl expression, but most of the
# time that amounts to a simple regular expression.
#
# Examples:
#
# $ rn 's/\.jpeg$/.jpg/' *.jpeg ; converts all files ending in 'jpeg' to 'jpg' in the current folder.
# $ rn 's/\.bak$//' *.bak ; remove the '\.bak' extension from all files in the current folder.
# $ rn 'printf("%02d_%s", "$.", "$_")' *.txt ; give every file endind in 'txt' with a two-digit prefix in ascending order.
#
($op = shift) || die "Usage: $0 perlexpr [filenames]\n";
if (!@ARGV) {
@ARGV = <STDIN>;
chomp(@ARGV);
}
foreach (@ARGV) {
$was = $_;
eval $op;
die $@ if $@;
if (-e $_) {
print "wont overwrite existing $_ with $was\n";
next;
}
$ok = rename($was, $_) unless ($was eq $_);
$ok or print STDERR "fail rename($was, $_): $!\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment