Replace text in folder names

How to replace the same text in folder names on Linux?

Say I have Photos_Jun, Photos_July, Photos_Aug, etc. The easiest way to rename them, for example, "Photos Jun", "Photos July", etc. (basically I want to replace the underscore with space "". I have about 200 such folders.

I was looking for a solution: How can I easily rename files using Perl?

It looks like I'm looking, but I don’t know how to make a regular expression to match folders that are alphanumeric and then β€œ_”.

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!

+4
source share
3 answers

if you are on * nix and you don't mind a solution without Perl, here is a shell solution (bash). delete echo when it is done.

 #!/bin/bash shopt -s extglob for file in +([a-zA-Z])*_+([a-zA-Z])/; do echo mv "$file" "${file//_/ }"; done 
+2
source

Linux has the rename command:

 rename '-' ' ' Photos_* 
+3
source
 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"; } 

Perform a single line translation:

 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 } 
0
source

Source: https://habr.com/ru/post/1307308/


All Articles