在 Automator 中使用脚本对目录结构 YYYY-MM-DD 中的文件进行分类,从文件名中获取它

问题描述 投票:0回答:1

拥有数千张没有元数据日期的图片和视频,但名称中带有日期结构(例如:YYYYMMDD_HHMMSS.jpg),想要将它们分类到带有日期的文件夹中,YYYY-MM-DD。

这个想法是在Automator中使用一个动作文件夹,所以当我在那里添加图片时,它们会自动分类。

我在 Automator 中尝试使用此代码,但即使没有给出错误,它也不会执行任何操作:

dest_dir=/Users/..........
# pattern to grab 4 digits of year 2 digits of month and 2 of the day
file_pattern="_([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2})"
for file in test_file_*; do
  [[ ! -f $file ]] && continue  # look at regular files only
  if [[ $file =~ $file_pattern ]]; then
    year="${BASH_REMATCH[1]}"
    month="${BASH_REMATCH[2]}"
    day="${BASH_REMATCH[3]}"
    destination_dir="$dest_dir/$year-$month-$day"
    [[ ! -d $destination_dir ]] && mkdir -p "$destination_dir"
    echo "Moving $file to $destination_dir"
    mv "$file" "$destination_dir"
  fi
done

The code on Automator Example of the structure

bash macos shell automator
1个回答
0
投票

你几乎已经拥有它了。您正在检查文件名中

_
之后的部分。我更新的示例已检查正确的字段:

更新:应用反馈中的修复。

dest_dir=/Users/myuser/photo-archive

for file in test_file_*; do
  [[ -f $file ]] || continue  # look at regular files only
  if [[ $file =~ ^([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2}) ]]; then
    year=${BASH_REMATCH[1]}
    month=${BASH_REMATCH[2]}
    day=${BASH_REMATCH[3]}
    destination_dir=$dest_dir/$year-$month-$day
    mkdir -p "$destination_dir"
    echo "Moving $file to $destination_dir"
    mv "$file" "$destination_dir"
  fi
done

此外,如果目录已存在,

mkdir -p
不会失败或发出警告。这是它的好处之一。

此外,在

var=$other_var
形式中,双引号不是必需的,除非该行包含文字空格,即
var="$foo $bar"

© www.soinside.com 2019 - 2024. All rights reserved.