shell脚本监控文件夹文件实现自动上传数据到hive表

createtb.sh

#!/bin/bash

#string="tablename;field1,field2,field3,field4;partition1,partition2,partition3"
string=$*
group=(${string//;/ })
for i in ${group[@]};do
    ((m++))
    if [[ m -eq 1 ]];then
        tables=$i
    elif [[ m -eq 2 ]];then
        fields=$i
    else partitions=$i
    fi
done
# echo "tables:" $tables
# echo "fileds:" $fields
# echo "partitions:" $partitions
# echo "-----------------"
field=(${fields//,/ })
partition=(${partitions//,/ })

# 创建表目录
$(mkdir -p /home/hive/observation/$tables)

# 数据库名称,这里不作为参数用自变量写了
database="observation"
# hive 拼接语句,分为h1,h2,h3
# h1是建表语句的前半部,h2是参数列表中间部分,h3是建表语句的后半部
h1="create external table $database.$tables"
# 在当前目录下创建文本文件temp,如果文件存在则清空文件
$(> temp)
# for 循环将参数追加到当前目录的temp文件,逗号分隔,echo -n 不换行
for i in ${field[@]};do
	echo -n $i" varchar(255)," >> temp
done
# h2取temp文本里的字符串
temp=$(cat temp)
# 将字符串最后的一个逗号去掉
h2="( ${temp%*,} )"
# 在当前目录下创建文本文件tmp,如果文件存在则清空文件
$(> tmp)
# for 循环将参数追加到当前目录的temp文件,逗号分隔,echo -n 不换行
for i in ${partition[@]};do
	echo -n $i" varchar(255)," >> tmp
done
# h3取temp文本里的字符串
tmp=$(cat tmp)
# 将字符串最后的一个逗号去掉
# h3是建表语句的后半部
h3="
partitioned by
( ${tmp%*,} )
row format delimited 
fields terminated by ','
lines terminated by '\n'
stored as textfile
location '/user/hive/warehouse/$database.db/$tables';
"
echo $h1$h2$h3
#$(hive -e "$h1$h2$h3")
$(rm -rf tmp temp)

echo "-------create hive table successfully--------"

#/bin/bash /home/hive/loadtb.sh
#exec /home/hive/loadtb.sh
#source /home/hive/loadtb.sh
#fork /home/hive/loadtb.sh
# 第一个参数为表名,第二个参数为分区字段
/home/hive/loadtb.sh $tables $partitions

loadtb.sh

#!/bin/bash

echo "----load hive table-----"
# 第一个参数为表名
table=$1
# 第二个参数为分区字段
partitions=$2
# load data directory 
DIR=/home/hive/observation/$tables
partkey=(${partitions//,/ })
# 分区数为$m
let m=${#partkey[@]}

h1="load data local inpath '/home/hive/observation/$table"
h3="' into table observation.$table partition"
allfiles=$(ls /home/hive/observation/$table/*.txt)
# 遍历目录,得到具体分区名称
for file in ${allfiles};do
	> part1
	# 取最后一个/前的文件名称
	h2="${file##*/}"
	# 去掉文件名后缀.txt
	str=${h2%%.*}
	# 分区名称分割,遍历文件名
	partvalue=(${str//_/ })
	# 分区拼接字符串
	for (( i=0;i<m;i++ ));do
		echo -n "${partkey[$i]}=${partvalue[$i]}," >> part1
	done
	h4_tmp=$(cat part1)
	h4="(${h4_tmp%*,});"
	echo "$h1/$h2$h3$h4"
	#hive -e "$h1$h2"
	#hive -e "load data local inpath '/home/hive/observation/$table' into table observation.$table partition(partition1=$i,partition2=$i);"
done

$(rm -rf part1)

执行命令

sh createtb.sh "tablename;field1,field2,field3,field4,field5,field6,field7;partition1,partition2"

运行效果

发布了159 篇原创文章 · 获赞 44 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq262593421/article/details/105561730
今日推荐