我有一个旧的 postgresql 转储,大小为 1.4GB,包含数百个表及其数据。
在该文件中,首先是所有建表语句,然后是所有数据插入。
我可以使用以下方法将文件分成两个:
file_name=synapse.sql
# devider:
STR='-- Data for Name:'
# number of lines befotre the devider that should get into the bottom file already:
D=2
# get first occurrence of devider:
K=$(grep -n -- $STR $file_name |head -1|cut -d":" -f1)
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K + $D))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
(来源:https://stackoverflow.com/a/3066968/1069083)
顶部文件现在看起来像这样:
--
-- Name: access_tokens; Type: TABLE; Schema: public; Owner: someone
--
CREATE TABLE access_tokens (
...
);
ALTER TABLE access_tokens OWNER TO "someone";
--
-- Name: application_services; Type: TABLE; Schema: public; Owner: someone
...
底部文件如下所示:
--
-- Data for Name: access_tokens; Type: TABLE DATA; Schema: public; Owner: someone
--
COPY access_tokens (id, user_id, device_id, token, last_used) FROM stdin;
4 @dagobertderkaufhauserpresser:matrix.test.com \N MDAxZWxvY2F0aW9uIG1hdHJpeC5lY2xhYnMuZGUKMDAxM2lkZW50aWZpZXIga2V5CjAwMTBjaWQgZ2VuID0gMQowMDQxY2lkIHVzZXJfaWQgPSBAZGFnb2JlcnRkZXJrYXVmaGF1c2VycHJlc3NlcjptYXRyaXguZWNsYWJzLmRlCjAwMTZjaWQgdHlwZSA9IGFjY2VzcwowMDFkY2lkIHRpbWUgPCAxNDU2ODY5OTY0MDk0CjAwMmZzaWduYXR1cmUgqG8q57PffosB-Aob1Szapvu-Bd7j9Sve9-6nPz7hL8QK \N
5 @wobwob:matrix.test.com \N MDAxZWxvY2F0aW9uIG1hdHJpeC5lY2xhYnMuZGUKMDAxM2lkZW50aWZpZXIga2V5CjAwMTBjaWQgZ2VuID0gMQowMDJiY2lkIHVzZXJfaWQgPSBAd29id29iOm1hdHJpeC5lY2xhYnMuZGUKMDAxNmNpZCB0eXBlID0gYWNjZXNzCjAwMWRjaWQgdGltZSA8IDE0NTY4NzM3MTI3NzMKMDAyZnNpZ25hdHVyZSB-PHutqfj3BAB6Mtop5qdiAz70YGSL2Wz7v1w4gj83Zgo \N
...
那么,现在如何将底部文件拆分为单独的文件,每个文件以表的名称作为文件名?
答案1
csplit -s -f file. bottom_$file_name '/^-- Data for Name:/-1' '{*}'
grep -oP '^-- Data for Name:\s*\K[^;]+' file.* | tr ':' ' ' | xargs -l -t mv
在一个新目录中,放置您生成的底部 sql 文件。然后csplit
将其拆分为多个文件并将它们放入file.nnn
格式名称中。之后,我们grep
从这些分割文件中取出表名并将它们xargs
传递到mv
.