[英]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.