簡體   English   中英

Ubuntu Bash腳本按時間順序更改文件名

[英]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

應該做的伎倆。

關於nullglobfailglob :如果沒有匹配*.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM