Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re^2: Changing filename extensions

by supernova95 (Initiate)
on Nov 16, 2021 at 04:03 UTC ( #11138866=note: print w/replies, xml ) Need Help??

in reply to Re: Changing filename extensions
in thread filenames

Okay so I have it working now! But I have one more question, is there a way to get my code to also account for files in subdirectories of the directory?

Replies are listed 'Best First'.
Re^3: Changing filename extensions
by jwkrahn (Monsignor) on Nov 16, 2021 at 04:32 UTC

    This may work (UNTESTED):

    #!/usr/bin/perl use strict; use warnings; use File::Find; @ARGV == 3 or die "usage: $0 DIR OLD_EXT NEW_EXT\n"; my $dir = $ARGV[ 0 ]; my $old = $ARGV[ 1 ]; my $new = $ARGV[ 2 ]; my @list; find sub { push @list, $File::Find::name if -f && /\.\Q$old\E\z/; }, $dir; foreach my $old_name ( @list ) { my $new_name = $old_name =~ s/\.\Q$old\E\z/.$new/r; rename $old_name, $new_name or die "Cannot rename '$old_name' beca +use: $!"; }
Re^3: Changing filename extensions
by Fletch (Bishop) on Nov 16, 2021 at 05:10 UTC

    You could use the -d test to look for entries that are themselves directories and then recurse down into them but at that point you'd have started down the path of reimplementing what something like Path::Tiny (or File::Find, or File::Find::Rule, or Path::Iterator::Rule, or . . .) could do for you off the shelf so you'd be better of using that to begin with.

    ## presuming your sample vars for dir, old, new ## Somewhat untested, but . . . use Path::Tiny qw( path ); my $iter = path( $dir )->iterator( { recurse => 1 } ); while( my $path = $iter->() ) { next unless $path->is_file and $path =~ m{\. $old $}x; my $new_path = $path->basename( $old ) . ".$new"; unless( my $ret = $path->move( $new_path ) ) { warn "Problem moving '$path': $ret\n"; } }

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re^3: Changing filename extensions
by hippo (Bishop) on Nov 16, 2021 at 09:37 UTC

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138866]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2022-07-02 02:10 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (102 votes). Check out past polls.