我有一些文件名如下:
01_dpm_gsi_182.sl5 02_dpm_devel_gsi_182.sl5 03_DPM_DSI_181.sl5 04_globus_httpd_122.sl5 05_globus_httpd_client_cgi_132.sl5
01_dpmgsi_s2011e01.sl5 02_dpmdevelgsi_s2011e02.sl5 .... ....
最接近我的建议是这样的:
#!/usr/bin/perl -n if (/^([^_]+)_(.+)_([^.]+)([.].+)$/) { my $s = $&; my $x = $1; my $y = $2; my $z = 2011; my $e = $4; $y =~ s/_//g; print "mv $s ${x}_${y}_s${z}e$x$e\n" }
然后像这样使用它:
# ls | perl -n reName.pl > output # bash ./output
有没有更好的方法或单行做这个,可能使用sed / awk?干杯!!
解决方法
没有必要使用bash脚本来mv文件,perl可以做到这一点.下面的脚本使用
File::Copy来实现此目的.我已经注释掉了执行移动的行,因此可以首先使用输入测试脚本.
码:
use strict; use warnings; use v5.10; #use File::Copy; my $year = 2011; for (@ARGV) { my ($pre,@p) = split /_/; my $ext = pop @p; $ext =~ s/.*\./s${year}e$pre./; my $new = join '_',$pre,(join '',@p),$ext; say "old: $_"; say "new: $new"; say "------"; #move $_,$new or die $!; }
用法:
perl script.pl *.sl5
如果您没有版本5.10,请用print打印并添加换行符.
输出:
old: 01_dpm_gsi_182.sl5 new: 01_dpmgsi_s2011e01.sl5 ------ old: 02_dpm_devel_gsi_182.sl5 new: 02_dpmdevelgsi_s2011e02.sl5 ------ old: 03_DPM_DSI_181.sl5 new: 03_DPMDSI_s2011e03.sl5 ------ old: 04_globus_httpd_122.sl5 new: 04_globushttpd_s2011e04.sl5 ------ old: 05_globus_httpd_client_cgi_132.sl5 new: 05_globushttpdclientcgi_s2011e05.sl5