本教程将探讨将文件从特定扩展名更改为另一个扩展名的疾速办法。咱们将为此应用 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’
www.51cto.com/it/news/2019/1230/17971.html
news.163.com/17/1212/09/D5EQJ2A400014AEE.html
news.163.com/17/0606/10/CM89AAKB00018AOP.html
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命令。