教你在 Centos8 中如何更改文件夾里多個文件的擴展名
方法一:使用循環(huán)
在目錄中遞歸更改文件擴展名的最常見方法是使用 shell 的 for 循環(huán)。我們可以使用 shell 腳本提示用戶輸入目標(biāo)目錄、舊的擴展名和新的擴展名以進行重命名。以下是腳本內(nèi)容:
- [root@localhost ~]# vim rename_file.sh
- #!/bin/bash
- echo "Enter the target directory "
- read target_dir
- cd $target_dir
- echo "Enter the file extension to search without a dot"
- read old_ext
- echo "Enter the new file extension to rename to without a dot"
- read new_ext
- echo "$target_dir, $old_ext, $new_ext"
- for file in *.$old_ext
- do
- mv -v "$file" "${file%.$old_ext}.$new_ext"
上面的腳本將詢問用戶要處理的目錄,然后 cd 進入設(shè)置目錄。接下來,我們得到?jīng)]有點.的舊擴展名。最后,我們獲得了新的擴展名來重命名文件。然后使用循環(huán)將舊的擴展名更改為新的擴展名。
其中${file%.$old_ext}.$new_ext意思為去掉變量$file最后一個.及其右面的$old_ext擴展名,并添加$new_ext新擴展名。
使用mv -v,讓輸出信息更詳細。
下面運行腳本,將/root/test下面的以.txt結(jié)尾的替換成.log:
- [root@localhost ~]# chmod +x rename_file.sh
- [root@localhost ~]# ./rename_file.sh
- Enter the target directory
- /root/test
- Enter the file extension to search without a dot
- txt
- Enter the new file extension to rename to without a dot
- log
- /root/test, txt, log
- renamed 'file10.txt' -> 'file10.log'
- renamed 'file1.txt' -> 'file1.log'
- renamed 'file2.txt' -> 'file2.log'
- renamed 'file3.txt' -> 'file3.log'
- renamed 'file4.txt' -> 'file4.log'
- renamed 'file5.txt' -> 'file5.log'
- renamed 'file6.txt' -> 'file6.log'
- renamed 'file7.txt' -> 'file7.log'
- renamed 'file8.txt' -> 'file8.log'
- renamed 'file9.txt' -> 'file9.log'
如果想將.log結(jié)尾的更改回.txt,如下操作: