house Tl
house Tl

Reputation: 11

rename files of a folder and its folders children

I would like to add prefix on all files in a folder and in all files in all of folder children.

Exemple :

 hello\file1
 hello2\file2
 file3
 file4 

the result should be after adding the prefix PRE_

 hello\PRE_file1
 hello2\PRE_file2
 PRE_file3
 PRE_file4 

i tried to do this :

find . -type f -exec rename 's/^/PRE_/' '{}' \;

but it modify all the name. Thank you

Upvotes: 0

Views: 215

Answers (1)

red0ct
red0ct

Reputation: 5055

Also you could use only perl if you want, without any additional modules:

use strict;
use warnings;

my ($prefix, $dir) = ('PRE_', '/home');
sub loop_dirs {
    my $path = $_[0];
    if (-d $path) { # if directory
         opendir my $dh, $path or die "$!";
         loop_dirs($path.'/'.$_) for grep ! /^\.{1,2}$/, readdir $dh; close $dh;
    } elsif (-e $path) { # if file
         prefix_add($path, $prefix); # do smth with file, e.g. rename
    }
}
sub prefix_add { my ($path, $pref) = @_; $path =~ s/([^\/]+)$/$pref$1/; rename $_[0], $path }
loop_dirs($dir);

This code works well both on Windows(ActivePerl) and Linux

Upvotes: 1

Related Questions