[英]Ubuntu Bash Script changing file names chronologicaly
我有这个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")
任何帮助将不胜感激。 感谢您的时间。
我总是惊讶地看到人们如何能得到在管线真正聪明grep
s到sed
至s awk
s到cut
s到head
S和tail
小号...
在您的特定情况下,您真的很幸运,因为date
命令可以格式化文件的修改日期(使用-r
选项)!
从而,
#!/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
:如果没有匹配*.txt
文件,那么脚本只是退出时出错(使用failglob
),或者,如果使用nullglob
,则没有任何反应,因为在这种情况下*.txt
会扩展为failglob
。
您粘贴的代码不完整。 将下面的代码与您的代码进行比较。
#!/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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.