我有一个包含多个create的文件master.sql。
master.sql
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;我想把这个文件分割成不同的文件--一个表一个。为此,我使用鲁宾氏解决方案这里。
下面是我使用的awk命令。
awk '/CREATE TABLE/{f=0 ;n++; print >(file=n); close(n-1)} f{ print > file}; /CREATE TABLE/{f=1}' master.sql在执行awk命令时,生成没有任何扩展名的表计数文件。尝试使用此文章联系
在创建每个sql文件时,我希望更改表名的文件名。
例如:
我正在尝试使用awk命令来获取表名表单master.sql。是否有可能在迭代master.sql时获得表名。
有办法绕道吗?
发布于 2022-01-10 03:48:27
下面是一个简单的2步过程:
# Split the files when the string CREATE TABLE is found
csplit master.sql '/CREATE TABLE/'
# Read the first line, extract table name and rename the file
for f in $(ls xx*);
do
table_name=`head -1 $f | awk '{ sub(/.*CREATE TABLE /, ""); sub(/ .*/, ""); print }'`
mv $f "$table_name.sql"
echo "Renaming $f to $table_name.sql";
done;->
Renaming xx00 to customers.sql
Renaming xx01 to inventory.sql->
$ ls
customers.sql inventory.sql master.sql
$ cat customers.sql
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
$ cat inventory.sql
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;发布于 2022-01-10 04:01:16
嗨,你可以用这样的词:
awk 'BEGIN{RS=";"} /CREATE TABLE/{fn = $3 ".sql"; print $0 ";" > fn; close(fn);}' master.sqlBEGIN块将使用;字符作为记录分隔符将输入拆分为sql语句(而不是行)。
然后,如果该行根据第三个字段(表名)将CREATE TABLE与文件名匹配,则可以打印语句内容。
注意:如果有任何包含;的sql注释,这可能就不太好用了。
编辑以关闭文件(见@ EDITED的注释)
发布于 2022-01-10 13:55:38
您使用的awk命令对于您所做的操作来说是非常复杂的。所需要的是:
awk '/CREATE TABLE/{close(n); n++} {print > n}' file对于您的新需求,这只是对以下几个方面的调整:
$ awk '/CREATE TABLE/{close(out); out=$3 ".sql"} {print > out}' file$ head *.sql
==> customers.sql <==
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
==> inventory.sql <==
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;https://stackoverflow.com/questions/70647373
复制相似问题