我有一个管道分隔的数据文件,没有标题。我需要将数据导入到 PostgreSQL 表中,从文件中第二列的数据开始,即跳过第一个“|”之前的数据对于每一行。如何使用 COPY 命令实现此目的?
使用剪切命令删除第一列,然后导入。
cut -d "|" -f 2- file1.csv > file2.csv
psql -d test -h localhost -c "\copy table(f1,f2,f3) from 'file2.csv' delimiter '|' csv header;"
不是与 postgresql 相关的答案,而是更多关于命令行工具的答案。
我最近也遇到了类似的问题。我用以下代码解决了它:
begin;
-- create temporary table, its columns NEED to match source file
-- you can also specify all columns manually, they just need to match file.
create temporary table tmp_table as select * from source_table where false;
-- either from file
copy tmp_table ('list of columns IN THE FILE' ) from '/data/table.csv' WITH (FORMAT csv, HEADER false);
-- or from gzip
copy tmp_table ('list of columns IN THE FILE' ) from program 'zcat /data/table.csv.gz' WITH (FORMAT csv, HEADER false);
-- you can add, drop, copmyte additional columns if needed
alter table tmp_table ADD COLUMN IF NOT EXISTS new_column date default NULL;
insert into source_table (columns, in, the, target, table) select columns, in, the, temp, table from tmp_table on conflict do nothing ;
drop table if exists tmp_table;
commit;