【问题标题】:How to check if there are jpg in a folder and then sort them by date in other folders in Bash?如何检查文件夹中是否有 jpg,然后在 Bash 的其他文件夹中按日期对它们进行排序?
【发布时间】:2022-11-11 15:37:54
【问题描述】:

我正在制作一个 Bash 脚本来排序在不同时间和日期(不是每天都有照片)进入文件夹的照片,如下所示。必须将照片移动到名为 PhotosOrder 的文件夹中,其中每天都有一个包含日期的文件夹。该任务在 Synology 服务器中执行,稍后它与 syncthing 同步到 Windows 服务器。首先我必须说我概括了它,因为我必须在许多不同的文件夹中执行它,并且我正在为每个文件夹复制脚本。这肯定是可优化的,但我们会在它工作后实现。脚本必须检查是否有 jpg 并将它们列在辅助变量 arr 中检查该列表在 if 中是否为空,如果是,则它什么也不做,但如果有 jpg,则它使:

为当天创建文件夹。 它计算了照片的数量,因为在不同的时间,不同的人放了照片,我想避免没有一张照片被覆盖。

考虑到之前的编号和我在开始时设置的名称参数,它会移动照片以重命名它们。 我不得不说我以后不能删除空文件夹,因为如果我不删除 syncthing 稍后用于同步的文件夹(我将该文件夹与另一台服务器上的文件夹同步)。到目前为止,一个替代脚本适用于我,它每天创建一个文件夹,无论是否有照片并移动它们(如果有的话),但是我必须手动删除空文件夹。如果我告诉脚本删除那些空文件夹,那么它会删除 syncthing 使用的文件夹,并且不再与其他服务器同步(此外我认为它也不是最佳的)。因此 if 循环在做任何事情之前检查是否有照片。

我现在拥有的脚本是这个:

这个:

#!/bin/sh

#values that change from each other

FOLDER="/volume1/obraxx/jpg/"
OBRA="-obraxx-"

#Create jpg listing in variable arr:

arr=$$(ls -1 /volume1/obraxx/jpg/*.jpg 2>/dev/null)

#if the variable is not empty, the if is executed:

if [[ !(-z $arr) ]]; then.

    #Create the folder of the day

    d="$(date +"%Y-%m-%d")"
    mkdir -p "$FOLDER"/PhotosOrdered/"$d"

    DESTINATION="$FOLDER/PhotosOrder/$d/"

    #Count existing photos:

    a=$$(ls -1 $FOLDER | wc -l)
    #Move and rename the photos to the destination folder.  

    for image in $arr; do
        NEW="$PICTURE$a"
        mv -n $image $DESTINATION$(date +"%Y%m%d")$NEW.jpg
       let a++

    done

fi

【问题讨论】:

标签: bash jpeg synology


【解决方案1】:
  • shebang 行应该看起来像#!/bin/bash,而不是#!/bin/sh
  • 您对数组的使用存在语法问题。
  • 您不应该解析ls 的输出。
  • 您正在计算源文件夹中的现有照片。它应该是 目标文件夹。
  • 您将当前日期放入文件夹名称和 文件名。 (不知道是不是这个要求。)
  • 变量OBRA 已定义但未使用。
  • 变量PICTURE 未定义。
  • 不建议对用户变量使用大写字母,因为 它们可能与系统变量冲突。

那么请您尝试以下方法:

#!/bin/bash

prefix="picture"                # new file name before the number
src="/volume1/obraxx/jpg/"      # source directory

# array "ary" is assigned to the list of jpg files in the source directory
mapfile -d "" -t ary < <(find "$src" -maxdepth 1 -type f -name "*.jpg" -print0)

(( ${#ary[@]} == 0 )) && exit   # if the list is empty, do nothing

# first detect the maximum file number in the destination directory
d=$(date +%Y-%m-%d)
dest="$src/PhotosOrder/$d/"     # destination directory
mkdir -p "$dest"
for f in "$dest"*.jpg; do
    if [[ -f $f ]]; then        # check if the file exists
        n=${f//*$prefix/}       # remove substings before prefix inclusive
        n=${n%.jpg}             # remove suffix leaving a file number
        if (( n > max )); then
            max=$n
        fi
    fi
done

a=$(( max + 1 ))                # starting (non-overwriting) number in the destination

# move jpg files renaming
for f in "${ary[@]}"; do
    new="$prefix$a.jpg"
    mv -n -- "$f" "$dest$new"
    (( a++ ))                   # increment the file number
done

【讨论】:

    最近更新 更多