shell腳本:批量修改文件名(文件名中添加字符)

舉例以下:批量建立10個隨機字符串的文件,要求每一個文件名後面添加_aaa,後綴名不變;html

[root@localhost goodboy]# ls正則表達式

adddbbdedf.html  baacjaiija.html  bhcfaabcfh.html  dgjdcdfbca.html  efejadfdji.htmlbash

agdhcdeaje.html  bgffbffjcg.html  cbbiebdafh.html  diadebbhag.html  jcajafgejf.htmlide

腳本1:spa

[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


解釋說明:htm

使用sed替換,正則表達式第1個()括號裏面表明文件名即\1;中間. 使用\進行脫意,表明分隔符;字符串

第2個括號裏面表明後綴html內容即\2;it

使用此方法須要在替換中添加.符號;class


更改後的效果以下:sed

[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:

#!/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'`


你們有更好的方法,歡迎分享知識~

相關文章
相關標籤/搜索