【发布时间】:2019-07-25 14:56:08
【问题描述】:
所以,我有一个 txt 文件,其中包含以下内容:
CREATE EXTERNAL TABLE `table1`(
`tab_id bigint COMMENT 'The unique identifier of thetable')
ROW FORMAT SERDE
*
STORED AS INPUTFORMAT
*
OUTPUTFORMAT
*
LOCATION
*
TBLPROPERTIES (
'transient_lastDdlTime'='1556u3ehw27')
CREATE TABLE `table2`(
`count` bigint)
ROW FORMAT SERDE
*
STORED AS INPUTFORMAT
*
OUTPUTFORMAT
*
LOCATION
'hdfs://path/'
TBLPROPERTIES (
'transient'='15407')
如您所见,在每个表的 DDL 之后,没有 ;最后。我正在尝试编写一个插入 ; 的程序在每个 DDL 表之后。所以输出应该是这样的:
CREATE EXTERNAL TABLE `table1`(
`tab_id bigint COMMENT 'The unique identifier of thetable')
ROW FORMAT SERDE
*
STORED AS INPUTFORMAT
*
OUTPUTFORMAT
*
LOCATION
*
TBLPROPERTIES (
'transient_lastDdlTime'='1556u3ehw27');
CREATE TABLE `table2`(
`count` bigint)
ROW FORMAT SERDE
*
STORED AS INPUTFORMAT
*
OUTPUTFORMAT
*
LOCATION
'hdfs://path/'
TBLPROPERTIES (
'transient'='15407');
我尝试了两种方法。 (1) 通过添加DDL创建脚本和python程序。
下面是我的 DDL 创建 .sh 脚本,它贯穿我的数据库表并为数据库中的所有表生成一个文件。我尝试使用下面最后一行显示的 cat 函数(# cat...)这样做但一直收到错误。
hiveDBName=my_db;
showcreate="show create table "
showpartitions="show partitions "
terminate=";"
tables=`hive -e "use $hiveDBName;show tables;"`
tab_list=`echo "${tables}"`
rm -f ${hiveDBName}_all_table_partition_DDL.sql
for list in $tab_list
do
echo "Generating table script for " ${hiveDBName}.${list}
showcreatetable=${showcreatetable}${showcreate}${hiveDBName}.${list}${terminate}
done
echo " ====== Create Tables ======= : " $showcreatetable
##Remove the file
rm -f ${hiveDBName}_extract_all_tables.txt
hive -e "use $hiveDBName; ${showcreatetable}" > /home/path/filter_ddls/aa.sql
grep -v "WARN" /home/path/filter_ddls/aa.sql >/home/path/hive_db_ddls/${hiveDBName}_extract_all_tables.sql
# cat a1.sql + ";\n\n" >> ${hiveDBName}_extract_all_tables.sql
下面是我的 Python 程序,但是这个方法的输出增加了;仅在跳过某些表的 tblproperties 之后。
import re
f = open("/home/path/ddl.sql", 'rt', encoding='latin-1').read()
with open("/home/path/new_ddl.sql","w") as output:
output.write(re.sub(r'(TBLPROPERTIES \(.*?\))', r'\1;', f, flags=re.DOTALL))
有什么想法或建议可以实现这一点吗?首选第一个选项(.sh 脚本)。
【问题讨论】:
-
如果你的文件格式没有改变并且
transient总是在需要添加之前出现在行中,你可以简单地使用sed来添加它们sed '/transient/s/$/;/' file -
我是 shell 脚本的新手。您知道如何将其合并到上面的代码中吗?
-
文本文件名是什么?生成文本文件后,您可以将其放置在脚本中的任何位置。 (根据它的生成方式,您甚至可以通过
sed命令将生成文本文件的任何内容的输出通过管道输出并写出成品)为什么在tables被填充后要执行tab_list=`echo "${tables}"?你只是在强迫分词发生? -
文本文件名为aa.sql。我可以和你聊天吗?
-
当然,只要我们中的一个人看到“继续聊天”按钮(并不总是显示),我很高兴与您聊天。你可以做什么添加
sed '/transient/s/$/;/' aa.sql,这将在')'之后添加';'。
标签: regex python-3.x shell unix hive