4

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: 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!

Community
  • 1
  • 1
dannyb
  • 43
  • 2
  • Thanks everyone who answered, the non-perl solution worked best for me. I had a few dashes to remove, and it worked well for that as well when I replaced the _ with -. – dannyb Apr 19 '10 at 02:07

3 Answers3

3

Linux has a rename command:

rename '-' ' ' Photos_*
Paul Richter
  • 6,154
  • 2
  • 20
  • 22
2

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
  • 327,991
  • 56
  • 259
  • 343
0
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
  • 126,886
  • 32
  • 213
  • 327