bash练习7(同一路径下的文件更改后缀)

#!/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


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值