【问题标题】:Rename files ordered by date重命名按日期排序的文件
【发布时间】:2015-03-29 08:46:19
【问题描述】:

我在使用这个脚本时遇到了问题:

#!/bin/bash
echo -n "Digit new name (no spaces and special chars!): "
read newname

echo -e "\n"

i=0

if test "$(ls -A | grep [.]jpg)"; then
    for f in "$(ls -Atr | grep [.]jpg)"; do
        let i=i+1
        #mv "$f" "$(printf "${newname}_%03d.jpg" "$i")"
        echo "$f renamed in: " $(printf "${newname}_%03d.jpg" "$i")
    done
    echo -e "\n\033[1;33;41m$i substituded!\033[0m\a"
else
    echo -e "\n\033[1;33;41mNothing was done!\033[0m\a"
fi
sleep 3

exit

我的问题是替换所有文件,但按日期排序(旧的优先)。 在上面的脚本中,我正在使用echo 进行测试,结果是所有文件列表都被重命名为一个文件。

【问题讨论】:

    标签: bash batch-rename


    【解决方案1】:

    问题是你引用了"$(ls -Atr | grep [.]jpg)",所以你得到的只是一个包含所有文件名的长字符串。

    这是一个更好的尝试:

    #!/bin/bash
    read -p "Digit new name (no spaces and special chars!): " newname
    echo
    i=0
    if test "$(ls -A | grep [.]jpg)"; then
        while IFS= read -r f; do
            let i=i+1
            #mv "$f" "$(printf "${newname}_%03d.jpg" "$i")"
            echo "$f renamed in: " $(printf "${newname}_%03d.jpg" "$i")
        done < <(ls -Atr | grep [.]jpg)
        echo -e "\n\033[1;33;41m$i substituded!\033[0m\a"
    else
        echo -e "\n\033[1;33;41mNothing was done!\033[0m\a"
    fi
    

    注意我正在使用:

    read -p "Digit new name (no spaces and special chars!): " newname
    

    代替:

    echo -n "Digit new name (no spaces and special chars!): "
    read newname
    

    -p 选项用于此目的,并在标准错误中输出文本。


    更新答案

    这里是一个增强的方法也支持特殊字符

    #!/bin/bash
    shopt -s nullglob
    read -p "Digit new name (no spaces and special chars!): " newname
    echo
    if test "$(ls -A | grep [.]jpg)"; then
        while read -r f; do
            ((i++))
            f=${f:1:((${#f}-2))} # remove the leading and trailing '
            f=${f//\\\"/\"}      # removed the \ before any embedded "
            f=$(echo -e "$f")    # interpret the escaped characters
            echo "$f renamed in: " $(printf "${newname}_%03d.jpg" "$i")
            #mv "$f" "$(printf "${newname}_%03d.jpg" "$i")"
            #file "$f"           # it's useful to test the script
        done < <(ls -Atr --quoting-style=c *.jpg .*.jpg)
    else
        echo -e "\n\033[1;33;41mNothing was done!\033[0m\a"
    fi
    

    你可以看到更解释的答案here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多