如何将 Find 的输出排序为 psql 复制命令以按顺序加载数据?
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;" \;
这会加载文件中的数据,但不会对文件进行排序。通过谷歌搜索,我知道你可以像这样输入 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
我希望从多个文件夹中的一堆文件中将数据加载到 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;" \;
这会加载文件中的数据,但不会对文件进行排序。通过谷歌搜索,我知道你可以像这样输入 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