Shell Script

定理:如果需要经常重复做某一项工作,那么就一定有让电脑自动完成的方法。

国际标准时间2月1日,又到了每月初提供最新下载包的时候了。今天一犯懒,写了个 Shell Script,扫描指定目录下当月新增的剧本,打包,然后移动到相应的目录,再把该目录打包。整个脚本运行起来不到1分钟,就把每月需要10分钟左右的手工工作做完了,而且在仔细审查了代码之后,可以肯定不会出错。 表情

当前目录分布情况:pdf 和 txt 目录包含每月产生的剧本,同级 script 目录下的 PDF Format 和 TXT Format 包含所有的剧本,按照编号(1□□□、2□□□等等)分出子目录。脚本的原理就是先把当月的文件打包,然后按字母顺序排列组合出可能的文件名集,若该类文件名存在,则移至相应的目录,并把该目录打包。仅此而已。注意:文件名第二位有字母的需要先处理。比如7h*若留在后面,就会与更广泛的7*所吻合而被提前处理掉。

帖出来用于处理 pdf 格式的脚本 zippdf,处理 txt 的大同小异。有在 Unix 下面玩儿的朋友欢迎交流经验。

#!/bin/sh
# Go to monthly directory.
cd pdf/
# Remove old zips, if there is any.
rm -f *.zip
# Pack this month's files.
zip newp *
# Go through from 7a* to 7z*
for findex in a b c d e f g h i j k l m n o p q r s t u v w x y z;
do
filename="7$findex*.pdf"
dirname="7""$findex""00p"
# If the pattern matches:
if ls $filename
then
# Move files to the corresponding directory
mv -f ./$filename "$HOME/script/PDF Format/$dirname/"
cd "$HOME/script/PDF Format/$dirname/"
# Pack this directory
zip -r "$HOME/pdf/""$dirname"".zip" *
cd "$HOME/pdf/"
fi
done
# Go through from 9a* to 9z*
for findex in a b c d e f g h i j k l m n o p q r s t u v w x y z;
do
filename="9$findex*.pdf"
dirname="9""$findex""00p"
# If the pattern matches:
if ls $filename
then
# Move files to the corresponding directory
mv -f ./$filename "$HOME/script/PDF Format/$dirname/"
cd "$HOME/script/PDF Format/$dirname/"
# Pack this directory
zip -r "$HOME/pdf/""$dirname"".zip" *
cd "$HOME/pdf/"
fi
done
findex=1
# Go through from 1* to 9*
while [ $findex -le 9 ]
do
filename="$findex*.pdf"
dirname="$findex""000p"
# If the pattern matches:
if ls $filename
then
# Move files to the corresponding directory
mv -f ./$filename "$HOME/script/PDF Format/$dirname/"
cd "$HOME/script/PDF Format/$dirname/"
# Pack this directory
zip -r "$HOME/pdf/""$dirname"".zip" *
cd "$HOME/pdf/"
fi
findex=`expr $findex + 1`
done

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注