process filenames with spaces
October 9, 2014
Perl
I have some files whose filenames are like this:
[some thing there]Sed & awk, 2nd Edition[some thing there].mobi
[some thing there]Erlang Programming[some thing there].mobi
[some thing there]Hacking Vim7.2[some thing there].mobi
[some thing there]Learning the vi and Vim Editors[some thing there].mobi
I want to rename them and delete the spaces in the filename.
so… I wrote a script in perl.
#!/usr/bin/env perl
#===============================================================================
# FILE: filename.pl
# AUTHOR: Phoenix Ikki (liuxueyang.github.io), liuxueyang457@gmail.com
# ORGANIZATION: Hunan University
# CREATED: 10/05/2014 09:10:59 AM
#===============================================================================
use strict;
use warnings;
use utf8;
use 5.014;
for (@ARGV) {
if ($_ =~ /\[.*\](.*)\[.*\].mobi/) {
# if ($_ =~ /(.*).zip/) {
my @lst = split / /, $1;
my $newname = join '', @lst;
$newname = $newname . '.mobi';
say "newname = $newname";
if ( -e $newname ) {
warn "can not rename $_ to $newname: $newname exists\n";
} elsif (rename $_ => $newname) {
} else {
warn "rename $_ to $newname failed: $!\n";
}
}
}
The results are:
Sed&awk,2nd Edition.mobi
ErlangProgramming.mobi
HackingVim7.2.mobi
LearningtheviandVimEditors.mobi
Problem Solved…