改进正则表达式以重命名文件



我需要帮助来提高用于递归重命名目录中文件的自定义函数的性能。函数如下所示:

# Rename the files to Kebab Case recursively
# @param {string} $d directory name
renameToKebab() {
d="${1:-$(pwd)}"
# replace whitespaces and underscores with hyphens
find $d -execdir rename 's/[ _]/-/g' '{}' +
# put a hyphen between words that are in Camel/Pascal case
find $d -execdir rename 's/([a-z])([A-Z])/$1-$2/g' '{}' +
# replace two or more hyphens with a single hyphen
find $d -execdir rename 's/-+/-/g' '{}' +
# replace -( with (
find $d -execdir rename 's/(-/(/g' '{}' +
# replace )- with )
find $d -execdir rename 's/-)/)/g' '{}' +
# transform upper case letters into lower case
find $d -execdir rename 'y/A-Z/a-z/' '{}' +
}
# Rename the files to underscore case recursively
# @param {string} $d directory name
renameToUnderscore() {
d="${1:-$(pwd)}"
find $d -execdir rename 's/[ -]/_/g' '{}' +
find $d -execdir rename 's/([a-z])([A-Z])/$1_$2/g' '{}' +
find $d -execdir rename 's/_+/_/g' '{}' +
find $d -execdir rename 's/(_/(/g' '{}' +
find $d -execdir rename 's/_)/)/g' '{}' +
find $d -execdir rename 'y/A-Z/a-z/' '{}' +
}

此函数是用bash编写的,位于~/.bash_profile中。rename命令是一个终端工具,它使用正则表达式重命名文件Perl。我不熟悉Perl.

上述脚本的问题是它执行了六次rename命令。因此,每次运行这些功能时,重命名文件都需要几秒钟。我想优化正则表达式,所以我只需要执行一次/两次rename。这将使事情变得更快。

提前谢谢。

注意重命名版本:0.20 操作系统: 乌班图 18

下面是如何在 Perl 中进行所有处理的示例,无需多次调用findrename外部命令。我只显示第一个函数renameToKebab()

#! /usr/bin/env perl
use feature qw(say);
use strict;
use warnings;
use Cwd qw(getcwd);
use File::Find;
sub rename_to_kebab {
my $d = shift || getcwd();
find(&rename_to_kebab_helper, $d);
}
sub rename_to_kebab_helper {
my $orig_name = $_;
return if ($_ eq ".") || ($_ eq ".."); 
# replace whitespaces and underscores with hyphens
s/[ _]/-/g;
# put a hyphen between words that are in Camel/Pascal case
s/([a-z])([A-Z])/$1-$2/g;
# replace two or more hyphens with a single hyphen
s/-+/-/g;
# replace -( with (
s/(-/(/g;
# replace )- with )
s/-)/)/g;
# transform upper case letters into lower case
y/A-Z/a-z/;
return if $_ eq $orig_name;
if ( -e $_ ) {
say "File '$_' exists in directory: ", $File::Find::dir;
say "   -> skipping";
return;
}
my $success = rename $orig_name, $_;
if ( !$success ) {
say "Could not rename '$orig_name' to '$_': $!";
}
}

最新更新