一个批量重命名文件名的shell脚本

来源:互联网 发布:手机视频 会议 软件 编辑:程序博客网 时间:2024/05/16 04:50

 问题:

文件夹下有如下文件:

 

-rw-r--r--   1 root root 139000 Sep 19 09:25 code.mass.zip
-rw-r--r--   1 root root  71473 Jun  5  2007 code.tar.gz
-rw-r--r--   1 root root  17419 Sep  5  2000 index.html
drwxr-xr-x   2 root root   4096 Sep 27 11:49 test1 JLKJL
drwxr-xr-x   2 root root   4096 Sep 27 11:49 test2 kkkk
drwxr-xr-x   2 root root   4096 Sep 27 11:49 test3 llll
drwxr-xr-x   2 root root   4096 Sep 27 11:49 test4 uuu
-rw-r--r--   1 root root  22789 Jun  5  2007 workaround.html
drwxr-xr-x   2 root root   4096 Aug  2  2007 workaround_files

 

想把 test2 kkkk 这种文件重命名为 tt2_kkkk 这样的文件名,脚本如何处理?

 

结果:

for file in *; do echo $file | grep -q 'test[1-4].*'; if [ $? = 0 ]; then newname=`echo $file |sed 's/test/([1-4]/) */(.*/)/tt/1_/2/g'`; mv "$file" $newname; fi; done

 

即:

for file in *;

do

    echo $file | grep -q 'test[1-4].*';

    if [ $? = 0 ];

    then

        newname=`echo $file |sed 's/test/([1-4]/) */(.*/)/tt/1_/2/g'`;

        mv "$file" $newname;

    fi;

done

 

中间的难点是 文件名中本来有空格,这个需要处理。