【问题标题】:Copy files (images) to folder structured according to creation date将文件(图像)复制到根据创建日期结构化的文件夹
【发布时间】:2019-06-23 13:39:23
【问题描述】:

我在 OSX 上使用 bash 脚本,它将所有图像从 SD 卡复制到我的外部硬盘。

脚本如下所示:

#!/bin/bash 
now=$(date +"%d%m%Y") 
mkdir -p /Volumes/WDigital/Images/Project1/$now 
find /Volumes/Untitled/DCIM/ -name '*.JPG' -print0 | xargs -0 -J % rsync --progress --times % /Volumes/WDigital/Images/Project1/$now

此脚本根据当前日期创建一个文件夹并将所有图像复制到此目的地。

我想稍微修改一下这个脚本,以便将每个图像复制到以特定图像的创建日期(与上次修改相同)命名的文件夹中。

所以如果我有 3 个文件,例如:

  • image1.jpg - lastModified: 08102016
  • image2.jpg - lastModified: 10102016
  • image3.jpg - lastModified: 08102016

我想在目的地 (/Volumes/WDigital/Images/Project1/) 获得 2 个文件夹

  • 文件夹 08102016 - 包含 image1 和 image3
  • 文件夹 10102016 - 包含 image2

我找到了可以在这里使用的“stat”命令 (Print a file's last modified date in Bash) 来获取修改日期,但我不确定如何正确地解决这个问题。

我的想法是有一个像(伪代码)这样​​的循环

#!/bin/bash 
for i in /Volumes/Untitled/DCIM/*/*.jpg; do
  creationdate = stat -f "%Sm" -t "%d%m%Y" "$i"
  rsync --progress --times $i /Volumes/WDigital/Images/Project1/$creationdate
done

如何为路径 /Volumes/Untitled/DCIM//.jpg 使用 for 循环?

或者你们中有人知道正确解决方案的另一个方向吗?

谢谢

编辑:

这是我的工作代码(带有计数器):

#!/bin/bash 
counter=0
completefilenumber=$( find "/Volumes/Untitled/DCIM/" -type f -iname '*.JPG' | wc -l )
find "/Volumes/Untitled/DCIM/" -type f -iname "*.JPG" -print0 | while IFS= read -r -d $'\0' img; do
  counter=$((counter+1))
  echo "$img (Nr. ${counter}/${completefilenumber})" 
  creationdate=$(stat -f "%Sm" -t '%d%m%Y' $img)
  mkdir -p /Volumes/WDigital/Images/Project1/$creationdate
  rsync --times $img /Volumes/WDigital/Images/Project1/$creationdate
done
echo "Script done!"

【问题讨论】:

    标签: bash macos file date


    【解决方案1】:

    不确定您是如何使用统计数据的,ls 是一种打发时间的好方法。由于您想逐个文件,因此 rsync 可能有点繁重。一种解决方案:

    for file in /Volumes/Untitled/DCIM/*/*.jpg; do
        creationdate=$(ls -lt --time-style="+%m%d%y" "$file" | cut -d" " -f6)
        mkdir -p /Volumes/WDigital/Images/Project1/$creationdate
        cp $file /Volumes/WDigital/Images/Project1/$creationdate
    done
    

    【讨论】:

      【解决方案2】:

      我假设您的 stat 代码有效。您的“伪代码”非常接近正确。

      您需要做的就是捕获 stat 命令的输出,以便您可以将其分配给您的创建日期

      #!/bin/bash 
      for img in /Volumes/Untitled/DCIM/*/*.jpg; do
        creationdate=$(stat -f "%Sm" -t "%d%m%Y" "${img}")
        rsync --progress --times $img "/Volumes/WDigital/Images/Project1/${creationdate}"
      done
      

      查看“命令替换”。

      基本上,您可以将任何命令包装在 $() 中以捕获其输出。这使您可以将其分配给变量。它变得比这更复杂,并且有一些陷阱,但这是一般概念,一些谷歌搜索会带你到许多可以比我更好地解释它的文章。

      当它不是索引时也使用$i 让我感到困惑,所以我改变了它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多