[英]How to sort the output of Find to a psql copy command to load data in order?
我希望从多个文件夹中的一堆文件中将数据加载到 PostgreSQL 数据库中。 我必须按顺序加载它们(即文件夹 2020 中的文件必须在文件夹 2021 之前加载,依此类推)。 这是我目前拥有的:
find ~/data/inserts/ -type f -exec psql -h db1.cluster-xxxxx.us-east-1.rds.amazonaws.com -p 5432 dbname -U admin1 -c "\COPY public.db1(col1,col2) FROM '{}' DELIMITER ',' CSV HEADER;" \;
这会加载文件中的数据,但不会对文件进行排序。 通过谷歌搜索,我知道您可以将 pipe sort
为:
find ~/data/inserts/ -type f -print | sort -z | xargs -r0 echo
但我不确定如何将其应用于我的案例。 即使在阅读文档后,我也不确定如何使用xargs -r0
。
您需要-print0
而不是-print
作为find
参数:
#!/usr/bin/env bash
# Pipe the sorted null delimited output of find to while loop
find ./ -type f -print0 | sort -z |
while IFS= read -r -d '' input_file || [ -n "$input_file" ]; do
# Now execute the pgsql command to copy from STDIN rather than named file
psql \
-h db1.cluster-xxxxx.us-east-1.rds.amazonaws.com -p 5432 -U admin1 dbname \
-c "COPY public.db1(col1,col2) FROM STDIN DELIMITER ',' CSV HEADER;" \
<"$input_file" # This provide the input file as STDIN
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.