利用 Shell 批量把文件夾下的圖片從時(shí)間戳格式的名字改成年月日時(shí)分秒格式的名字。
知識點(diǎn):
- ls命令循環(huán)與篩選
- Shell 變量的定義與使用
- Shell 函數(shù)的定義、調(diào)用、參數(shù)的傳遞與獲取、返回值的獲取
- Shell 中使用正則表達(dá)式
- 字符串的基本操作
- 條件表達(dá)式與關(guān)系表達(dá)式
- date 命令轉(zhuǎn)換時(shí)間戳
- mv 命令
file.sh文件內(nèi)容:
# for循環(huán)
# ls 篩選查詢。-d:只列出目錄條目 *匹配一個或多個字符
# 將秒級的時(shí)間戳轉(zhuǎn)換成日期字符串 date -r 1548205689 '+%Y-%m-%d %H:%M:%S'
# 參考:
# 0 https://www.runoob.com/linux/linux-shell.html
# 1 https://blog.csdn.net/taiyang1987912/article/details/38929069
# 2 http://noahsnail.com/2016/11/12/2016-11-12-ls%E5%91%BD%E4%BB%A4%E4%BB%8B%E7%BB%8D/
# 3 https://man.linuxde.net/shell-script/shell-7
# 4 http://niliu.me/articles/1450.html#more-1450
# 5 https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash/806923
# 6 https://stackoverflow.com/questions/12187859/create-new-file-but-add-number-if-filename-already-exists-in-bash
# shell函數(shù)的定義與使用
isNumberStr() {
# echo "第一個參數(shù)為 $1 !"
# shell使用正則表達(dá)式驗(yàn)證是否數(shù)字
re='^[0-9]+$'
if ! [[ $1 =~ $re ]]; then
echo "Error: $1 is not a number."
return 0
else
# echo "Valid number."
return 1
fi
}
# format 2018-02-01 01:01:01
tryFormat() {
timestamp=$1
suffix=$2
index=$3
# 調(diào)用函數(shù)
isNumberStr $timestamp
# 獲取函數(shù)返回值
isNum=$?
# 條件表達(dá)式要放在方括號之間,并且要有空格
if [ $isNum -eq 1 ]; then
len=${#timestamp}
msLen=13
sLen=10
if [ $len -eq $msLen ]; then
timestamp=${timestamp:0:10}
fi
# shell表達(dá)式,注意是反引號``不是單引號''
# 注意系統(tǒng)中文件名中不能包含冒號(:)等特殊符號,這里如果寫成%H:%M:%S,寫入的時(shí)候會自動把冒號變?yōu)?。
ds=`date -r $timestamp '+%Y-%m-%d %H-%M-%S'`
regex='[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}-[0-9]{2}-[0-9]{2}'
if [[ $ds =~ $regex ]]; then
# echo "Is a timestamp"
# 重命名
oldFile=$1.$suffix
newFile=$ds.$suffix
# 因?yàn)樾碌奈募杏锌崭? # mv操作加-i遇到同名的詢問要不要覆蓋
if [[ -e "$newFile" ]]; then
echo "文件名重復(fù)了"
# 文件名重復(fù)的時(shí)候這里直接在文件名后面加上當(dāng)前index
newFile=$ds.$index.$suffix
fi
echo "$newFile"
mv -i $oldFile "$newFile"
else
echo "$timestamp is not a valide timestamp"
fi
fi
}
index=0
for file in $( ls -d {*.png,*.jpg,*.jpeg,*gif,*.PNG,*.JPG,*.JPEG,*GIF} )
do
let index++
echo "file: $file"
# 截取文件名 注意定義變量=前后不能有空格
# ${VAR%.* }含義:從$VAR中刪除位于 % 右側(cè)的通配符左右匹配的字符串,通配符從右向左進(jìn)行匹配。% 非貪婪 %% 貪婪。
fileName=${file%.*}
# echo $fileName
# 字符串長度
# fileNameLen=${#fileName}
# echo "fileName length= $fileNameLen"
# 子串
# echo ${fileName:0:3}
# ${VAR#*.} 含義:從 $VAR 中刪除位于 # 右側(cè)的通配符所匹配的字符串,通配符是左向右進(jìn)行匹配。# 非貪婪 ## 貪婪。
suffix=${file#*.}
# echo "suffix= $suffix"
# 調(diào)用函數(shù) 傳參
tryFormat $fileName $suffix $index
echo "---------------------------------------"
done
使用方法:把該文件拷貝到要批量處理的圖片文件夾下,然后在終端中執(zhí)行該shell文件。