Centos8中如何更改文件夾中多個文件的擴展名

本教程將討論將文件從特定擴展名更改爲另一個擴展名的快速方法。我們將爲此使用 shell循環、rename命令
方法一:使用循環

在目錄中遞歸更改文件擴展名的最常見方法是使用 shell 的 for 循環。我們可以使用 shell 腳本提示用戶輸入目標目錄、舊的擴展名和新的擴展名以進行重命名。以下是腳本內容:

[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"
done;

Centos8中如何更改文件夾中多個文件的擴展名Centos8中如何更改文件夾中多個文件的擴展名
上面的腳本將詢問用戶要處理的目錄,然後 cd 進入設置目錄。接下來,我們得到沒有點.的舊擴展名。最後,我們獲得了新的擴展名來重命名文件。然後使用循環將舊的擴展名更改爲新的擴展名。

其中${file%.$old_ext}.$new_ext意思爲去掉變量$file最後一個.及其右面的$old_ext擴展名,並添加$new_ext新擴展名。

使用mv -v,讓輸出信息更詳細。

下面運行腳本,將/root/test下面的以.txt結尾的替換成.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'

Centos8中如何更改文件夾中多個文件的擴展名Centos8中如何更改文件夾中多個文件的擴展名
如果想將.log結尾的更改回.txt,如下操作:
Centos8中如何更改文件夾中多個文件的擴展名Centos8中如何更改文件夾中多個文件的擴展名

方法二:使用rename命令

如果不想使用腳本,可以使用rename工具遞歸更改文件擴展名。如下是使用方法:

[root@localhost ~]# cd /root/test/
[root@localhost test]# rename .txt .log *.txt

Centos8中如何更改文件夾中多個文件的擴展名Centos8中如何更改文件夾中多個文件的擴展名
更改回.txt擴展名也同樣的操作:

[root@localhost test]# rename .log .txt *.log

Centos8中如何更改文件夾中多個文件的擴展名Centos8中如何更改文件夾中多個文件的擴展名

總結

本教程討論瞭如何將文件從特定擴展名更改爲另一個擴展名的快速方法。我們將爲此使用 shell循環、rename命令。

本文原創地址:https://www.linuxprobe.com/centos-rename-ext.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章