本教程将讨论一种快速将文件从特定扩展名更改为另一个文件的方法。我们将使用shell循环,为此重命名命令。方法一:使用循环递归更改目录中文件扩展名的最常用方法是使用shell的for循环。我们可以使用shell脚本提示用户输入要重命名的目标目录、旧扩展名和新扩展名。以下是脚本内容:[root@localhost~]#vimrename_file.sh#!/bin/bashecho"Enterthetargetdirectory"readtarget_dircd$target_direcho"Enterthefileextensiontosearchwithoutadot"readold_extecho"Enterthenewfileextensiontorenametowithoutadot"readnew_extechcho"$target_dir,$old_extm*v$new_ext"forfilein-v"$file""${file%.$old_ext}.$new_ext"上面的脚本将询问用户要在哪个目录上工作,然后cd进入设置目录。接下来,我们得到没有点的旧扩展。最后,我们获得了重命名文件的新扩展。然后使用循环将旧扩展名更改为新扩展名。其中${file%.$old_ext}.$new_ext表示去掉变量$file的最后一部分。和右侧的$old_ext扩展名,并添加$new_ext的新扩展名。使用mv-v使输出更详细。运行下面的脚本,将/root/test下的.txt结尾替换成.log:[root@localhost~]#chmod+xrename_file.sh[root@localhost~]#./rename_file.shEnterthetargetdirectory/root/testEnterthefileextensiontosearchwithoutadottxtEnterthenewfileextensiontorenametowithoutadotlog/root/test,txt,log更名为'file10.txt'->'file10.log'更名为'file1.txt'->'file1.log'更名为'file2.txt'->'file2.log'更名为'file3.txt'->'file3.log'重命名'file4.txt'->'file4.log'重命名'file5.txt'->'file5.log'重命名'file6.txt'->'file6.log'重命名'file7.txt'->'file7.log'renamed'file8.txt'->'file8.log'renamed'file9.txt'->'file9.log'如果想把.log的结尾改回.txt,请执行下列操作:
