http://qs1969.pair.com?node_id=11138866


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 (Abbot) 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