Linux重命名多个文件扩展名

时间:2020-02-23 14:39:58  来源:igfitidea点击:

我们可以使用mv命令来更改文件名。
我们也可以使用它来更改文件扩展名。
但是,它仅适用于单个文件,并且不带通配符。

我们可以创建一个Shell脚本来一次更改多个文件的扩展名。

Linux Shell脚本更改多个文件的扩展名

让我们看一下脚本代码,我们将在for循环中使用mv命令来更改当前目录中所有文件的扩展名。

#!/bin/sh

#Save the file as multimove.sh

IFS=$'\n'

if [ -z "" ] || [ -z "" ]
then
echo "Usage: multimove oldExtension newExtension"
exit -1
fi
# Loop through all the files in the current directory
# having oldExtension and change it to newExtension
for oldFile in $(ls -1 *.)
do
# get the filename by stripping off the oldExtension
filename=`basename "${oldFile}" .`
# determine the new filename by adding the newExtension
# to the filename
newFile="${filename}."
# tell the user what is happening
echo "Changing Extension \"$oldFile\" --> \"$newFile\" ."
mv "$oldFile" "$newFile"
done

用法:multimove.sh doc txt(将所有.doc更改为.txt)

测试重命名Shell脚本

下面是上述程序执行的示例输出。

$ls
abc.txt		hi.doc		theitroad.doc	multimove.sh
$./multimove.sh doc txt
Changing Extension "hi.doc" --> "hi.txt" .
Changing Extension "theitroad.doc" --> "theitroad.txt" .
$ls
abc.txt		hi.txt		theitroad.txt	multimove.sh
$./multimove.sh txt doc
Changing Extension "abc.txt" --> "abc.doc" .
Changing Extension "hi.txt" --> "hi.doc" .
Changing Extension "theitroad.txt" --> "theitroad.doc" .
$ls
abc.doc		hi.doc		theitroad.doc	multimove.sh
$

脚本假设和局限性

  • 文件名只有一个句号(.),不能是.tar.gz这样的

  • 它仅循环遍历当前目录中的所有文件。
    但是,您可以扩展它以在子目录中查找文件。

  • 文件名中的空格可能会导致脚本出现问题。
    它在我的系统上可以使用带有空格的文件名,但是我不能保证它也对您有用。