views:

119

answers:

3

How can I replace the same text in folder names in linux?

Say I have "Photos_Jun", "Photos_July", "Photos_Aug", etc. whats the simplest way I can rename them like "Photos Jun", "Photos July", etc (basically I want to replace the underscore with a space " ". I have about 200 of these folders.

I was looking at solution: http://stackoverflow.com/questions/1836563/how-can-i-easily-bulk-rename-files-with-perl

It looks like what im looking for however, I dont know how to make a regular expression to match folders that are alphanumeric followed by a "_".

All files have non-numeric names, so I think [a-zA-Z] is the right way to start.

perl -e 'foreach $f (glob("File\\ Name*")) { $nf = $f; $nf =~ s/(\d+)$/sprintf("%03d",$1)/e; print `mv \"$f\" \"$nf\"`;}'

Thanks for any help!

+1  A: 
perl -e 'use File::Copy; foreach my $f (glob("*")) { next unless -d $f; my $nf = $f; $nf =~ s/_/ /g; move($f, $nf) || die "Can not move $f to $nf\n"; }

Tu unroll the one-liner:

use strict; # Always do that in Perl. Keeps typoes away.
use File::Copy; # Always use native Perl libraries instead of system calls like `mv`
foreach my $f (glob("*")) {
    next unless -d $f; # Skip non-folders
    next unless $f =~ /^[a-z_ ]+$/i; # Reject names that aren't "a-zA-Z", _ or space
    my $new_f = $f; 
    $new_f =~ s/_/ /g; # Replace underscore with space everywhere in string
    move($f, $nf) || die "Can not move $f to $nf: $!\n";
                     # Always check return value from move, report error
}
DVK
+1  A: 

if you are on *nix and you don't mind a non Perl solution, here's a shell (bash) solution. remove the echo when satisfied.

#!/bin/bash
shopt -s extglob
for file in +([a-zA-Z])*_+([a-zA-Z])/; do echo mv "$file" "${file//_/ }"; done
ghostdog74
this worked, i had to remove "echo" for it to work, thanks!
dannyb
small amendment. if you only want folders, put a slash behind. see edit.
ghostdog74
+2  A: 

Linux has a rename command:

rename '-' ' ' Photos_*
Paul Richter