将 Unix 文件的内容复制到 Postgres 表列

问题描述 投票:0回答:1

我有一个要求,即在 Unix 路径上接收 XML 文件。我想将此 xml 文件的内容复制到 Postgres 表中的一列中。

在以下位置收到示例文件:/home/bojack/test.xml

<address>
   <street>Main Street</street>
   <city>New York</city>
   <country>USA</country>
</address>

想要将其复制到包含 2 列的表格中,

id value
1  <address>
   <street>Main Street</street>
   <city>New York</city>
   <country>US</country>
   </address>

有人可以帮忙吗?

xml postgresql shell unix pgadmin
1个回答
0
投票

首先是表格:

# CREATE TABLE test_table(id serial, value text);
CREATE TABLE

然后,让我们为元素添加一个随机属性:

$ cat file
<address>
   <street some="attribute">Main Street</street>
   <city>New York</city>
   <country>USA</country>
</address>

现在使用 awk 来读取整个文件,复制内容中的所有双引号并将双引号复制到开头和结尾:

$ awk '                   # tested with gawk, mawk and awk version 20121220
BEGIN {
    RS="^$"               # slurp in the whole file
}
{
    gsub(/"/,"\"\"")      # double the double quotes
    gsub(/^"*|"*$/,"\"")  # add quotes to the beginning and end
    print                 # out
}' file

上面 awk 的输出:

"<address>
   <street some=""attribute"">Main Street</street>
   <city>New York</city>
   <country>USA</country>
</address>
"

现在使用 awk 处理文件并将其提供给 psql:

$ awk 'BEGIN{RS="^$"}{gsub(/"/,"\"\"");gsub(/^"*|"*$/,"\"");print}' file |
> psql -h host -d dbname -c "\copy test_table(value) from '/dev/stdin' csv" -U username
Password: 
COPY 1

最后:

# select * from test_table ;
 id |                      value                       
----+--------------------------------------------------
  1 | <address>                                       +
    |    <street some="attribute">Main Street</street>+
    |    <city>New York</city>                        +
    |    <country>USA</country>                       +
    | </address>                                      +
    | 
(1 row)

这是在 Linux 中使用 Bash shell 进行测试的。

© www.soinside.com 2019 - 2024. All rights reserved.