Reputation: 43
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!
Upvotes: 4
Views: 952
Reputation: 342373
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
Upvotes: 2
Reputation: 129403
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
}
Upvotes: 0