需求:
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