重命名按日期排序的文件

时间:2014-12-29 10:49:18

标签: bash batch-rename

我在使用此脚本时出现问题:

#!/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进行测试,结果是所有文件列表都在一个文件中重命名。

1 个答案:

答案 0 :(得分:4)

问题是你引用"$(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