首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按日期重命名文件

问按日期重命名文件
EN

Stack Overflow用户
提问于 2014-12-29 10:49:17
回答 1查看 106关注 0票数 1

我对这个剧本有困难:

代码语言:javascript
复制
#!/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进行测试,结果是所有的文件列表都在一个文件中重命名。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-29 11:00:13

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

这将是一个更好的尝试:

代码语言:javascript
复制
#!/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

注意我用的是:

代码语言:javascript
复制
read -p "Digit new name (no spaces and special chars!): " newname

而不是:

代码语言:javascript
复制
echo -n "Digit new name (no spaces and special chars!): "
read newname

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

更新答复

这里是一个增强的方法,它也支持特殊的chars

代码语言:javascript
复制
#!/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。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27687412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档