Shell脚本:批量拷贝

一、需求

将指定目录下的特定格式的文件拷贝到指定目录下

二、代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#! /bin/bash

#需要传入两个参数
if [ $# -ne 3 ]; then
echo "USAGE: sh $0 srcPath targetPath fileReg"
echo "eg: sh $0 /mnt/bigdan1 / '*.txt'"
exit 1
fi

#获取两个参数
srcPath=$1
targetPath=$2

#判断传入的两个参数是否存在
if [ ! -d "$srcPath" ]; then
echo "$srcPath does not exist"
exit 1
fi

if [ ! -d "$targetPath" ]; then
echo "$targetPath does not exist"i
exit 1
fi

#第三个参数为正则表达式
REG=$3

#获取srcPath下的所有文件
for dir in $(ls $srcPath)
do
if [[ $dir =~ $REG ]]; then #过滤出符合正则规则的文件
path=$srcPath$dir #拼凑文件路径
echo "begin copy $dir from $srcPath to $targetPath...`date`"
cp -r $path $targetPath
echo "finish copy $dir from $srcPath to $targetPath! `date`"
fi
done

exit 0

三、知识点

① shell中正则匹配需要在[[ ]]内进行;

② shell中使用 =~ 完成正则匹配。

四、演示

五、易错点

说明:[[ ]]是bash内建的,需要使用bash来执行,使用sh是执行不了的。