遇到需要批量更改文件名的需求 所以写了脚本 测试通过
由于时间有点紧 所以需要调整的地儿还是挺多的
不足的地是不能递归子文件夹 之后有时间补上 需要说明的是 set 内置命令 它可以将其后的命令输出结果转化为新参数,覆盖之前的$1 .. $N
剩下用到的小技巧就是用到了替换
1 #!/bin/bash
2
3 ##
4 # mv batch file_name only this directory
5 # $1 path
6 # $2 original string
7 # $3 destination string
8 # $4 replace times default 0 all others one time
9 ##
10
11
12 # estimate parameter
13 if [ $# -lt 3 -a $# -gt 4 ] ; then
14
15 echo "this script must 3 or 4 parameter !"
16 echo "$1 path $2 original string $3 destination string $4 replace times default 0 all others one time!" 1>&2
17 exit 1
18 fi
19
20 # estimate $1 is path
21 if [ ! -d $1 ]; then
22 echo "$1 must be a file!" 1>&2
23 exit 2
24 fi
25
26 if [ $# -eq 4 ] ; then
27 times=$4
28 else
29 times=0
30 fi
31
32 # set variables value
33 path=$1
34 orig=$2
35 dest=$3
36
37 cd $1
38 set $(ls $1| grep $orig)
39
40 for file in $@
41 do
42 if [ -f $file ] ; then
43 if [ $times -eq 0 ] ; then
44 newName=${file//$orig/$dest}
45 else
46 newName=${file/$orig/$dest}
47 fi
48 `mv $file $newName`
49 else
50 continue
51 fi
52 done
53
54 if tes $? -eq 0
55 then
56 echo -e "files have renamed already! \n"
57 fi