使用文件名对Bash中的文件进行排序

时间:2017-12-17 08:48:20

标签: bash escaping mv quoting

我尝试使用Bash脚本对照片和视频文件进行排序。文件格式简单" YYYY-MM-DD hh.mm.ss" (例如2017-10-26 17.31.36.JPG)。我想根据年份和月份将文件排序到文件夹中。这是我写的脚本:

#!/bin/bash
LC_ALL=C
photo_path="/share/Usb/Temp/test/"
declare months
months=(["1"]="Jan\ " ["2"]="Feb\ " ["3"]="Mar\ " ["4"]="Apr\ " ["5"]="May\ " ["6"]="Jun\ " ["7"]="Jul\ " ["8"]="Aug\ " ["9"]="Sep\ " ["10"]="Oct\ " ["11"]="Nov\ " ["12"]="Dec\ ")

for filename in *; do
    str_len=$(expr ${#filename})
    year=$(echo $filename | cut -c1-4)
    month_num=$(echo $filename | cut -c6-7)
    short_year=$(echo $filename | cut -c3-4)     
    month=${months[$month_num]}$short_year'/'
    dest="$photo_path$year/$month."
    first_name=$(echo $filename | cut -c1-10)
    second_name=$(echo $filename | cut -c12-$str_len)
    name="$first_name\ $second_name"

    if [[ $year =~ ^-?[0-9]+$ ]];
    then
        echo "Moving $name to $dest"
        mv "$name" "$dest"
    fi

done

然而,当我运行脚本时,我得到一个像这样的错误代码

Moving 2017-10-26\ 17.31.36.JPG to /share/Usb/Temp/test/2017/Oct\ 17/.
mv: can't rename '2017-10-26\ 17.31.36.JPG': No such file or directory

在评论之后,我将代码修改为:

for filename in *; do
    year=${filename:0:4}
    month_num=${filename:5:2}
    short_year=${filename:2:2}
    month=${months[$month_num]}$short_year'/.'
    dest="$photo_path$year/$month"

    if [[ $year =~ ^-?[0-9]+$ ]];
    then
        echo "Moving $filename to $dest"
        mv "${filename}" "${dest}"
    fi

done

但是,我仍然收到以下错误消息:

Moving 2017-10-23 08.56.46.JPG to /share/Usb/Temp/test/2017/Oct\ 17/.
mv: can't rename '2017-10-23 08.56.46.JPG': No such file or directory

我可以知道应该怎么做来修复代码吗?

0 个答案:

没有答案