首页 > 解决方案 > 循环将变量分配给文件名的片段,然后在命令中为目录中的每个文件使用

问题描述

我想将文件上传到日期分区的 s3 对象中。我在目录中有很多文件,并且想将每个文件移动到从文件名中的日期派生的文件夹结构中。

for file in /home/ec2-user/clickparts/t*; do year="${file:9:4}"; month="${file:14:2}"; day="${file:17:2}"; aws s3 cp "$file" s3://bk-py-dev/json/clicks/clickpartition/$year/$month/$day/; done

如果我能以这种单行格式做到这一点,那就太棒了。文件名格式为 the_date=2019-03-05.json

标签: bashloopsamazon-s3

解决方案


你已经有了一个很好的解决方案。另一种选择是

topdir="bk-py-dev/json/clicks/clickpartition"
while IFS=- read -r xxxyear month dayjson; do
   aws s3 cp "${xxxyear}-${month}-${dayjson}" s3://${topdir}/${xxxyear#*=}/${month}/${dayjson%.*}
done < <(find * -maxdepth 0 -type f -name '*.json' )

我不知道你为什么要把它放在一行中。你可以用你喜欢
的代码添加一个函数,现在你可以调用 oneliner 。.bashrcupload2s3() {..}upload2s3


推荐阅读