in reply to rename file name in directory and subdir

Is it for a specific directory?

If so something like this might work, although I can't test it on windows at the moment:

#!/usr/bin/perl use strict; use warnings; my $path = 'C:\folder1\folder2\'; my @newName = split (/\\/, $path); shift(@newName); my $rename = join(".", @newName); opendir (my $directory, $path) or die $!; while(readdir $directory) { next if $_ =~ m/^\./; my $fileName = "$rename" . ".$_"; rename $_, $fileName; }

Replies are listed 'Best First'.
Re^2: rename file name in directory and subdir
by choroba (Cardinal) on Aug 06, 2013 at 20:30 UTC
    Beware, \' is special in single quotes.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thank you choroba, well spotted. Reason #121 not to use windows!! That would make it 'C:\folder1\folder2\\'. Is that right?

      EDIT:People who use perl on windows must be that bit sharper, having to account for file separators also escaping special characters in perl code.

        I have been caught forgetting to double my backslashes in a Windows environment more times that I would wish to publicly recall.
Re^2: rename file name in directory and subdir
by starface245 (Novice) on Aug 06, 2013 at 20:35 UTC
    It not specific

    c:\folder1 has many files
    a.txt
    b.txt
    c.txt
    output
    .folder1.a.txt
    .folder2.b.txt
    .folder3.c.txt

    then c:\folder1\folder2 (in subdir)
    abc.txt
    cde.txt
    cfe.txt
    output
    .folder1.folder2.abc.txt
    .folder1.folder2.cde.txt
    .folder1.folder2.cfe.txt
    and so on....
      I rarely work with windows, and can't check this on windows, so you would have to switch the file separators in this. Also, I'm not certain that it's entirely safe to modify the @pathList array from the subroutine during the for loop. In any case this works for me, changing all the filenames in folders from the original path downwards:

      #! /usr/bin/perl use strict; use warnings; use diagnostics; my $originalPath = '/Path/To/file/'; my @pathList = ("$originalPath"); redoName($originalPath); for (@pathList) { redoName($_); } sub redoName { my $path = $_[0]; my @newName = split (/\//, $path); shift(@newName); my $newName = join(".", @newName); opendir (my $directory, $path) or die $!; while(readdir $directory) { my $fullName = "$path" . "$_"; unless (-d $fullName) { next if $_ =~ m/^\./; my $fileName = "$path" . "$newName" . ".$_";; rename $fullName, $fileName or die "couldn't r +ename: $!\n"; } if (-d "$fullName") { next if $_ =~ m/^\./; my $newPath = "$path" . "$_" . "\/"; push (@pathList, $newPath); } } }