将当前目录下的.txt后缀名修改为.ini
1,bash
#!/bin/bash
for files in `ls | grep .txt`
do
mv $files `echo $files | sed 's/\.txt/\.ini/'`
done
另外可以简单一条命令即可,rename .txt .ini * 也可以通配符,rename .txt .ini a*表明替换开始字符为a的文件
说明rename专门为重命名文件设计的,可以看出跟mv的区别
2,python脚本
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
def rename():
path = input("请输入要处理的文件夹路径") #python使用raw_input
print (path)
old_ext = "."+input("请输入要处理的文件类型")
print (old_ext)
new_ext = "."+input("请输入你想变成的文件类型")
print (new_ext)
for (path, dirs, files) in os.walk(path):#遍历目录树
for filename in files:
ext = os.path.splitext(filename)[1] #取得文件类型,注意它还带着点号
print (ext)
if(ext == old_ext):
print ("----------------")
newname = filename.replace(old_ext, new_ext)
oldpath = path + "/" + filename
newpath = path + "/" + newname
try:
os.rename(oldpath, newpath)
except BaseException as e:
print(str(e))
if __name__ == '__main__':
rename()