当前位置:Linux教程 - Shell - shell - 文件序列a1,a2,a3...a11,a12...a1000改成a0001,a0002...a1000?

shell - 文件序列a1,a2,a3...a11,a12...a1000改成a0001,a0002...a1000?

文件序列a1,a2,a3...a11,a12...a1000改成a0001,a0002...a1000?
2004-04-23 15:18 pm
来自:Linux文档
现载:Www.8s8s.coM
地址:无名

$cat test
ls a* > tempfile1
sed 's/a//' tempfile1 > tempfile2
awk '{printf("mv a%s a%04s ", $0, $0)}' tempfile2 > tempfile3
chmod 700 tempfile3
./tempfile3
rm tempfile*
$chmod test

----------------------------------------------------------------
ls a*|awk '{
num=substr($1,2,length($1)-1);
printf "mv %s a%04d ",$1,num
}'>rename.sh

sh rename.sh

----------------------------------------------------------------
for file in a*
do
newfile=`echo $file | awk '{printf "a%04d", substr($1, 2, length($1)-1)}'`
mv $file $newfile
done

给个不用awk的,效率会低一点
ls -1 a*|while read j
do
num=`echo $j|cut -b 2-`
num=`printf a%04s $num`
mv $j $num
done

-----------------------------------------------------------------
稍微缩减一下:
for file in a*
do
mv $file `echo $file|awk '{printf "a%04d", substr($1,2,length($1)-1)}'`
done

如果a1,a2,a3...等文件是各自有不同的扩展名呢?就像a1.pxx,a2,baa,a3.tga...
这样是不是可以呢:
for file in a*
do
nam=`echo $file|cut -d. -f1`
exe=`echo $file|cut -d. -f2`
mv $file `echo $nam|awk '{printf "a%04d", substr($1,2,length($1)-1)}'`.$exe
done