Ubuntu Bash脚本按时间顺序更改文件名

时间:2012-12-01 04:30:52

标签: bash ubuntu

我有这个bash脚本,我试图将目录中的所有* .txt文件更改为上次修改的日期。这是脚本:

#!/bin/bash
# Renames the .txt files to the date modified
# FROM: foo.txt  Created on: 2012-04-18 18:51:44
# TO:    20120418_185144.txt
for i in *.txt
do
mod_date=$(stat --format %y "$i"|awk '{print $1"_"$2}'|cut -f1 -d'.'|sed 's/[: -]//g') 
mv "$i" "$mod_date".txt
done

我得到的错误是:

renamer.sh: 6: renamer.sh: Syntax error: word unexpected (expecting "do")

非常感谢任何帮助。谢谢你的时间。

2 个答案:

答案 0 :(得分:2)

我总是惊讶地看到人们如何能够通过grepsedawkcut通过headtail s date。 } s和-r s ...

在您的特定情况下,您真的很幸运,因为#!/bin/bash # It's a good idea to use one of the two: shopt -s failglob # shopt -s nullglob for i in *.txt; do mod_date=$(date -r "$i" +'%Y%m%d_%H%M%S') mv "$i" "$mod_date.txt" done 命令可以格式化文件的修改日期(使用nullglob选项)!

因此,

failglob

应该这样做。

关于*.txtfailglob:如果没有匹配nullglob的文件,则脚本只会退出并显示错误(使用*.txt时),或者,如果使用{{1}},没有任何反应,因为在这种情况下{{1}}会扩展为空。

答案 1 :(得分:0)

您粘贴的代码不完整。将下面的代码与您的代码进行比较。

#!/bin/bash
# Renames the .txt files to the date modified
# FROM: foo.txt  Created on: 2012-04-18 18:51:44
# TO:    20120418_185144.txt
for i in *.txt
do
    mod_date=$(stat --format %y "$i"|awk '{print $1"_"$2}'|cut -f1 -d'.' | sed 's/[: -]//g')
    mv "$i" "${mod_date}.txt"
done