Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl, how can I rename files in all subdirectories of a drive?

How can I rename all files on a drive with .wma and .wmv extensions to .txt extension using Perl regardless how deep they are in the directory structure?

like image 269
User1611 Avatar asked Dec 04 '22 15:12

User1611


1 Answers

See perldoc File::Find. The examples in the documentation are pretty self-explanatory and will get you most of the way there. When you have an attempt, update the question with more information.

If this is a learning exercise, you will learn better by first trying to do yourself.

UPDATE:

Assuming you have had a chance to look into how to do this yourself and taking into account the fact that various solutions have been posted, I am posting how I would have done this. Note that I would choose to ignore files such as ".wmv": My regex requires something to come before the dot.

#!/usr/bin/perl

use strict;
use warnings;

use File::Find;

my ($dir) = @ARGV;

find( \&wanted, $dir );

sub wanted {
    return unless -f;
    return unless /^(.+)\.wm[av]$/i;
    my $new = "$1.txt";
    rename $_ => $new
        or warn "'$_' => '$new' failed: $!\n";
    return;
}

__END__
like image 161
Sinan Ünür Avatar answered May 20 '23 11:05

Sinan Ünür