#!/usr/bin/bash
# 更改文件后缀名,用法:change_ext.sh 路径 原来的扩展名 新的扩展名
# change_ext.sh path old_ext new_ext
if [ $# -ne 3 ]
then
echo "usage: change_ext.sh path old_ext new_ext"
exit 1
fi
FILEPATH=$1
OLD_EXT=$2
NEW_EXT=$3
if [ ! -d ${FILEPATH} ]
then
echo "The Path:${FILEPATH} is not existed or not a directory"
exit 1
fi
OLDPATH=$(pwd)
cd ${FILEPATH}
if [ $? -ne 0 ]
then
echo "cannot walk in the directory: ${FILEPATH}"
exit 1
fi
FILES=$(ls | grep -E ".*\.${OLD_EXT}")
#echo ${FILES}
NUMS=0
for FILE in ${FILES}
do
FILEBASE=${FILE%.${OLD_EXT}}
NEWFILENAME=${FILEBASE}.${NEW_EXT}
mv ${FILE} ${NEWFILENAME}
if [ $? -eq 0 ]
then
let NUMS++
echo "change file name: ${FILE} TO ${NEWFILENAME} successfully"
else
echo "Failed to change file name: ${FILE} TO ${NEWFILENAME}"
fi
done
cd ${OLDPATH}
echo "Total Files changed: ${NUMS}"
测试:
[root@gyl-huawei bash]# mkdir ext # 当前路径下新建一个目录ext
[root@gyl-huawei bash]# cd ext
[root@gyl-huawei ext]# touch file{1..10}.txt # 在ext目录下新建10个后缀位txt的文件
[root@gyl-huawei ext]# ls
file10.txt file1.txt file2.txt file3.txt file4.txt file5.txt file6.txt file7.txt file8.txt file9.txt
[root@gyl-huawei ext]# cd ..
[root@gyl-huawei bash]# ./change_ext.sh ext txt new # 测试脚本
change file name: file10.txt TO file10.new successfully
change file name: file1.txt TO file1.new successfully
change file name: file2.txt TO file2.new successfully
change file name: file3.txt TO file3.new successfully
change file name: file4.txt TO file4.new successfully
change file name: file5.txt TO file5.new successfully
change file name: file6.txt TO file6.new successfully
change file name: file7.txt TO file7.new successfully
change file name: file8.txt TO file8.new successfully
change file name: file9.txt TO file9.new successfully
Total Files changed: 10
[root@gyl-huawei bash]# ls ext # 查看ext目录下文件的后缀
file10.new file1.new file2.new file3.new file4.new file5.new file6.new file7.new file8.new file9.new