简体   繁体   中英

Perl Regex string replacement is not recognizing underscores in a string

I'm trying to batch rename a bunch of files using Perl and Regex. I've been able to change most things so far but I'm having trouble removing underscores. I've search and found several examples, all with similar syntax but for some reason it's not working for me.

Here's an an example of what my file names look like:

HP_1 Level 1 Geology_Plan_1_400dpi.jpg

Here's my code so far:

#  Declare directory path
my $dir = './Georeferenced_Images.tri/TEST/';

#  Initialization message
printf "Changing names...\n";

#  Remove spaces
my @list = glob("$dir/*");
for (@list) {
      my $orig = $_;
      s/\s+//g;
      move($orig, $_);  
}

#  Remove underscores
@list = glob("$dir/*");
for (@list) {
      my $orig = $_;
      s/_//g;
      move($orig, $_);  
}

The top part of the code removes the spaces. The second part of the code is not removing the underscores. I've played around with the code and it works if I do something like:

s/_Plan_//g;

It doesn't work if I just try to remove the underscores. Any help would be great!

Thanks

The problem is that your directory name contains an underscore. So when you remove all of the underscores from $_ , you change the name of the directory and the move() tries to move your renamed file into a renamed directory which (presumably) doesn't exist.

One solution is to use File::Basename to split $_ into the directory name and the filename and to only change the filename.

Another solution would be to change directory into $dir before calling glob() (and then removing $dir/ from the parameter you pass to glob() ).

You might have seen what the problem was is you have checked the return value of move() and displayed an appropriate error message.

move($orig, $_)
  or die "Could not move $orig to $_: $!";

Also note, that by printing out $orig and $_ before calling move() you would have a) probably seen what the problem was and b) realised that the problem has nothing to do with Perl's string replacement (as you would have seen that the replacement was carried out successfully). This is, surely, basic debugging practice and would have avoided (at the very least) you posting a question with a completely misleading title :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM