舉例如下:批量創建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,如需轉載請自行聯系原作者