手机版
你好,游客 登录 注册
背景:
阅读新闻

几个简单的Shell实例亲测

[日期:2012-08-07] 来源:Linux社区  作者:gdcsy [字体:大 中 小]
7.文件循环(文件切割)
说明:有的时候,我们不断地向一个文件追加内容,那么文件会变得很大,这段脚本是对大文件mv到新的文件名,同时再创建原文件,以达到文件切割的目的。

#!/bin/bash
#describe:wirte by chensiyao
#time:2012.8.3
ver="0.1"

#定义help函数
help()
{
cat <<HELP
rotatefile -- rotate the file name

USAGE: rotatefile [-h] filename

OPTIONS: -h help text
EXAMPLE: rotatefile out
This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1
and create an empty out-file
The max number is 10
version $ver
HELP

}

#定义error函数
error()
{
echo "$1"
exit 1
}

########主程序######
#当参数1不为空时

while [ -n "$1" ];do
case $1 in
-h)help;shift 1;;
--)break;;
-*)echo "error:no such option $1.-h for help";exit 1;;
*)break;;
esac
done

#如果参数为空
if [ -z "$1" ];then
error "ERROR:you must specify a file,use -h for help"
fi

#把$1赋值给filen
filen="$1"
#rename any .1,.2 etc file
#循环检查是否存在将转换的文件,它这里以1-8,说明备份的文件数为9个
#如果存在文件,或将先将文件命名为filen.(n+1)

for n in 8 7 6 5 4 3 2 1;do
if [ -f "$filen.$n" ];then
p=`expr $n "+" 1`
echo "mv $filen.$n $filen.$p"
mv $filen.$n $filen.$p
fi
done

#rename the origianl file
#备份文件
if [ -f "$filen" ];then
echo "mv $filen $filen.1"
mv $filen $filen.1
fi

#创建新的文件
echo touch $filen
touch $filen

linux
相关资讯       shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款