需求:某个目录下有若干日志文件,文件名是log.2011mmddhhmmss(mmddhhmmss为任意的时间戳),更改成log.2012mmddhhmmss。
这里必然用到正则表达式,首先想到一个Perl的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/usr/bin/perl if ($#ARGV != 0) { print "usage: command dirname"; exit(1); } my $basedir = $ARGV[0]; opendir(DIR, $basedir); @files = readdir(DIR); foreach (@files) { if ($_ =~ /log.2011d{10}/) { $newfile = $_; $newfile =~ s/(log.)(2011)(d*)/${1}2012$3/; rename $_, $newfile; } } |
用bash实现关键用for i in ls
来获得各个文件名,然后用管道和sed。
1 2 3 4 5 6 |
#!/usr/bin/bash cd $1; for file in `ls`; do mv $file `echo $file|sed 's/(log).2011(.*)/1.20122/'` done; |