本教程將討論將文件從特定擴展名更改爲另一個擴展名的快速方法。我們將爲此使用 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;
上面的腳本將詢問用戶要處理的目錄,然後 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'
如果想將.log結尾的更改回.txt,如下操作:
如果不想使用腳本,可以使用rename
工具遞歸更改文件擴展名。如下是使用方法:
[root@localhost ~]# cd /root/test/ [root@localhost test]# rename .txt .log *.txt
更改回.txt擴展名也同樣的操作:
[root@localhost test]# rename .log .txt *.log
本教程討論瞭如何將文件從特定擴展名更改爲另一個擴展名的快速方法。我們將爲此使用 shell循環、rename命令。