教你在 Centos8 中如何更改文件夹里多个文件的扩展名

本教程将讨论将文件从特定扩展名更改为另一个扩展名的快速方法。我们将为此使用 shell循环、rename命令。 ......
本教程将讨论将文件从特定扩展名更改为另一个扩展名的快速方法。我们将为此使用 shell循环、rename命令。

方法一:使用循环

在目录中递归更改文件扩展名的最常见方法是使用 shell 的 for 循环。我们可以使用 shell 脚本提示用户输入目标目录、旧的扩展名和新的扩展名以进行重命名。以下是脚本内容:

  1. [root@localhost ~]# vim rename_file.sh 
  2. #!/bin/bash 
  3. echo "Enter the target directory " 
  4. read target_dir 
  5. cd $target_dir 
  6.  
  7. echo "Enter the file extension to search without a dot" 
  8. read old_ext 
  9.  
  10. echo "Enter the new file extension to rename to without a dot" 
  11. read new_ext 
  12.  
  13. echo "$target_dir, $old_ext, $new_ext" 
  14.  
  15. for file in *.$old_ext 
  16. do 
  17.     mv -v "$file" "${file%.$old_ext}.$new_ext" 

上面的脚本将询问用户要处理的目录,然后 cd 进入设置目录。接下来,我们得到没有点.的旧扩展名。最后,我们获得了新的扩展名来重命名文件。然后使用循环将旧的扩展名更改为新的扩展名。

[SITESERVER_PAGE]

其中${file%.$old_ext}.$new_ext意思为去掉变量$file最后一个.及其右面的$old_ext扩展名,并添加$new_ext新扩展名。

使用mv -v,让输出信息更详细。

下面运行脚本,将/root/test下面的以.txt结尾的替换成.log:

  1. [root@localhost ~]# chmod +x rename_file.sh  
  2. [root@localhost ~]# ./rename_file.sh  
  3. Enter the target directory  
  4. /root/test 
  5. Enter the file extension to search without a dot 
  6. txt 
  7. Enter the new file extension to rename to without a dot 
  8. log 
  9. /root/test, txt, log 
  10. renamed 'file10.txt' -> 'file10.log' 
  11. renamed 'file1.txt' -> 'file1.log' 
  12. renamed 'file2.txt' -> 'file2.log' 
  13. renamed 'file3.txt' -> 'file3.log' 
  14. renamed 'file4.txt' -> 'file4.log' 
  15. renamed 'file5.txt' -> 'file5.log' 
  16. renamed 'file6.txt' -> 'file6.log' 
  17. renamed 'file7.txt' -> 'file7.log' 
  18. renamed 'file8.txt' -> 'file8.log' 
  19. renamed 'file9.txt' -> 'file9.log' 

[SITESERVER_PAGE]

如果想将.log结尾的更改回.txt,如下操作: