举例如下:批量创建10个随机字符串的文件,要求每个文件名后面添加_aaa,后缀名不变;
[root@localhost goodboy]# ls
adddbbdedf.html baacjaiija.html bhcfaabcfh.html dgjdcdfbca.html efejadfdji.html
agdhcdeaje.html bgffbffjcg.html cbbiebdafh.html diadebbhag.html jcajafgejf.html
脚本1:
1 2 3 4 5 6 7 8 9 | [root@localhost ~] # cat 02.sh #!/bin/bash #written by mofansheng@2016-02-17 path= /goodboy [ -d $path ] && cd $path for file in ` ls ` do mv $ file ` echo $ file | sed 's/\(.*\)\.\(.*\)/\1_aaa.\2/g' ` done |
解释说明:
使用sed替换,正则表达式第1个()括号里面代表文件名即\1;中间. 使用\进行脱意,代表分隔符;
第2个括号里面代表后缀html内容即\2;
使用此方法需要在替换中添加.符号;
更改后的效果如下:
1 2 3 4 5 6 7 8 9 10 11 | [root@localhost goodboy] # ll -rw-r--r-- 1 root root 0 2月 17 17:40 adddbbdedf_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 agdhcdeaje_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 baacjaiija_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 bgffbffjcg_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 bhcfaabcfh_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 cbbiebdafh_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 dgjdcdfbca_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 diadebbhag_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 efejadfdji_aaa.html -rw-r--r-- 1 root root 0 2月 17 17:40 jcajafgejf_aaa.html |
脚本2:
1 2 3 4 5 6 7 8 | #!/bin/bash #written by mofansheng@2016-02-17 path= /goodboy [ -d $path ] && cd $path for file in ` ls ` do mv $ file ` echo $ file | sed 's/\(.*\)\(\..*\)/\1_aaa\2/g' ` done |
解释说明:
同样使用sed替换,正则表达式,与上面的区别在于第2个括号里面的内容,代表.html 分隔符和后缀名为一体,替换内容的话不需要再单独加.点;.分隔符同样需要使用\进行脱意;
可以使用sed -r参数,看起来就清爽很多,不需要\脱意;
mv $file `echo $file|sed -r 's/(.*)(\..*)/\1_aaa\2/g'`
大家有更好的方法,欢迎分享知识~
本文转自 模范生 51CTO博客,原文链接:http://blog.51cto.com/mofansheng/1743016,如需转载请自行联系原作者