我已经在我的MacOS终端上设置了psql。它连接到我通过Amazon RDS运行的PostgreSQL数据库。
我有100个CSV文件(名称1、2、3、4最多100个)。我想批量导入它们。我看到有一些脚本(https://dba.stackexchange.com/questions/168861/import-100-csv-files-into-postgresql/169089#169089),但我不知道如何运行脚本。
我试着复制和粘贴这个脚本-
for x in $(ls <folder_name>*.csv);
do psql -c "copy table_name from '$x' csv" also; done我收到了这些错误-
db=> for x in $(ls <folder_name>*.csv);
ERROR: syntax error at or near "for"
LINE 1: for x in $(ls <folder_name>...
^
db=> do psql -c "copy <table_name> from '$x' csv" also; done
ERROR: syntax error at or near "psql"
LINE 1: do psql -c "copy <table_name> from '$x' csv" also;你能帮我a)找出正确的脚本来批量导入这些文件吗? b)找出如何执行脚本?
注意--所有文件都将写入同一个表中,该表已经存在。
发布于 2018-05-28 22:59:52
考虑下表:
CREATE TABLE t (id INT,description TEXT);和以下文件
file1.csv
id,description
1,foofile2.csv
id,description
2,bar执行以下shell脚本:
#!/bin/bash
path="/home/user/files/"
for f in $path*.csv;do
cat $f | psql testdb -c "COPY yourtable FROM STDIN DELIMITER ',' CSV HEADER"
done现在你有了你的数据:
$ psql testdb -c "SELECT * FROM t"
id | description
----+-------------
1 | foo
2 | bar
(2 Zeilen)发布于 2018-05-28 23:43:05
如果要将所有内容加载到同一个表中,并且可以排除标头,则可以选择将它们连接到单个csv中。
bash-$ head -1 /folder_name/file1.csv > combined_file.csv
bash-$ cat folder_name/*.csv | grep -v 'headerpattern' >>combined_file.csvpostgres# COPY yourtable FROM 'combined_file.csv' DELIMITER ','
https://stackoverflow.com/questions/50568907
复制相似问题