在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
使用perl自带函数rename可以重命名文件名称,具体用法,rename $old_name, $new_name。 例如,要把文件名中“7--1_F03_2018-12-28.fsa”中的前缀“7--”去除。 1 use strict; 2 3 my $DIR_PATH = "./"; # current directory 4 opendir TEMP, ${DIR_PATH} || die "Can not open this directory"; 5 my @filelist = readdir TEMP; #读取目录下的所有文件名 6 7 foreach (@filelist) { 8 my $tmp = $_; 9 if ( $tmp ne "." && $tmp ne ".." ) { #去掉当前目录和上级目录,非必须 10 if ( $tmp =~ /^7--(.+\.fsa)/ ) { #运用正则筛选需要替换的部分 11 rename( $DIR_PATH . $_, $DIR_PATH . $1); 12 } 13 } 14 }
再如调换A01_1.fsa名字中的下划线前后的顺序,简化版为: 1 use strict; 2 3 opendir TEMP, "./" || die "Can not open this directory"; 4 my @filelist = readdir TEMP; # 5 6 foreach (@filelist) { 7 if ( /(\d{1,2})_(\w{3}).fsa/ ) { 8 rename( "./$_", "./".$2."_".$1.".fsa" ); 9 } 10 }
use strict; use File::Copy qw(copy cp); opendir TEMP1, "./" || die "Can not open this directory TEMP1 $!"; my $res_dir = "rename".time(); mkdir $res_dir || warn "Can't create directory: $!"; my @filelist = readdir TEMP1; # foreach (@filelist) { if ( /\d{2}--(\d{1,2}).+fsa/ ) { copy( "./$_", $res_dir."/p2h2_".$1.".fsa" ); } }
关于perl的文件系统的操作实例,之前的例子还有: 脚本参阅
根据文件夹名称重名文件 利用cwd()获取路径在strict下会报错,所以注释掉。 #use strict; use Cwd(getcwd,cwd); #print getcwd(); if (cwd() =~ /(p\d{1,2})_\d{1,2}/){ my $block = $1; opendir TEMP, "./" || die "Can not open this directory"; my @filelist = readdir TEMP; # foreach (@filelist) { if ( /\S{2}_(\S{3})\.fsa/ ) { rename( "./$_", $block ."_". $1.".fsa" ); } } }else{ die "Directory Name is wrong"; } 如果要同时对多个目录进行操作可以用,glob操作符,然后用上述脚本;也可以在文件夹和文件名统一后,依次遍历,此外可以用File::Copy来代替Rename操作,后者相当于剪切,调试时容易弄丢原始数据。 use strict; use File::Copy qw(copy cp); opendir TEMP1, "./" || die "Can not open this directory TEMP1 $!"; my $res_dir = "result".time(); mkdir $res_dir || warn "Can't create directory: $!"; my @dir_list = readdir TEMP1; foreach(@dir_list){ if (/(p\d{1,2})_\d{1,2}/){ my $dir = $_; my $block = $1; opendir TEMP2, "./$dir/" || die "Can not open this directory TEMP2 $!"; my @file_list = readdir TEMP2; foreach (@file_list) { if ( /\S{2,3}_(\S{3})\.fsa/ ) { copy( "./$dir/$_", $res_dir."/".$block ."_". $1.".fsa" ); #or rename() } } closedir(TEMP2); } closedir(TEMP1); }
use strict; use File::Copy qw(copy cp); opendir TEMP1, "./" || die "Can not open this directory TEMP1 $!"; my $res_dir = "result".time(); mkdir $res_dir || warn "Can't create directory: $!"; my @dir_list = readdir TEMP1; foreach(@dir_list){ if (/(p\d{1,2})_\d{1,2}/){ my $dir = $_; my $block = $1; opendir TEMP2, "./$dir/" || die "Can not open this directory TEMP2 $!"; my @file_list = readdir TEMP2; foreach (@file_list) { if ( /\S{2,3}_(\S{3})\.fsa/ ) { copy( "./$dir/$_", $res_dir."/".$block ."_". $1.".fsa" ); #or rename } } closedir(TEMP2); } closedir(TEMP1); }
|
请发表评论