工作中遇到一個小需求,需要對一系列的檔案進行重新命名。
原始格式是string_1.obj,現在想把檔案名稱中的數字變成定長的,不足位元往前補零,即變成string_001.obj這種形式。
自己學著寫了個指令碼,很菜的,貼上來請大家指點一下。
#! /bin/bash# this script is used to rename files# the orignal filename is as XXXX_1.obj# and the final filename is as XXX_0001.obj the width of the num is given as a parameterrm result.txtexport suffix=".obj"find . -name "*$suffix" > result.txtcat result.txt | while read onelinedoexport orifilename=${oneline##*/} #cut off the path of filenameexport prefilename=${orifilename%_*} #without "_"export numfilename=${oneline##*_}export numfilename=${numfilename%.*} #get the num in filename((i=$1-${#numfilename})) #get the num of zero which is neededexport zeros=`echo $numfilename | awk '{printf "%0'"$i"'d",0}{print}'` export finalfilename=$prefilename"_"$zeros$suffix#echo "$orifilename, $finalfilename"#rename "s/$orifilename/$finalfilename/" ./$finalfilenamemv $orifilename $finalfilenamedoneecho "Done"