将here doc输出的内容保存到文件,当文件超过阈值,动态更新文件名

需求:

1. sqlplus查询结果保存到文件(脚本里我暂用cat代替sqlplus语句),文件名格式  <日期>_ <批号>,批号范围0000-9999;

2. 当文件大于2M自动替换文件名(批号部分加1),分割时要求保证数据完整性。

 

#!/bin/bash
#assume the threshold of the file size is 4byte
threshold=4
date=`date +%Y%m%d`
#batch num
count=0
func ()
{
    myline=$1
    file_name=${date}_$(printf "%04d" $count)
    echo $myline >> $file_name
    size=$(du -b $file_name | awk '{print $1}')
    if [ $size -ge $threshold ];then
        ((count++))
    fi
}
cat | while read line; do func $line; done <<EOF
1
2
3
4
5
6
7
8
9
0
EOF


我理解用sqlplus可以直接实现,但是我不会,只好用shell。

一开始我准备用split命令来按大小分割(split -d -b 2M -a 4)查询结果的,但是发现它分割的结果,查询结果内容可能会被截取,不符合需求。

收到chinaunix上jason680 的启发,我已经用 split -d -C 2M -a 4 /tmp/data [prefix] 实现了该功能,再次感谢他。

$ man split
NAME
split - split a file into pieces
...

-b, --bytes=SIZE
put SIZE bytes per output file

-C, --line-bytes=SIZE
put at most SIZE bytes of lines per output file

 

 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章