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

在unix/Linux环境中,mv是移动文件的命令,也可以使用它来更改文件扩展名。但它只适用于单个文件,也使用其它字符。

在这里,提供了一个简单的脚本,可以使用它来更改目录中多个文件的扩展名。

将所有.doc文件更改为.txt文件:multimove.sh -


#!/bin/sh

#Save file as multimove.sh

IFS=$'
'

if [ -z $1 ] || [ -z $2 ]
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 *.${1})
do
# get the filename by stripping off the oldExtension
  filename=`basename ${oldFile} .${1}`
# determine the new filename by adding the newExtension
# to the filename
  newFile=${filename}.${2}
# tell the user what is happening
  echo Changing Extension $oldFile --> $newFile .
mv $oldFile $newFile
done

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

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


pankaj:temp pankaj$ ls
abc.txt        hi.doc        journaldev.doc    multimove.sh
pankaj:temp pankaj$ ./multimove.sh doc txt
Changing Extension hi.doc --> hi.txt .
Changing Extension journaldev.doc --> journaldev.txt .
pankaj:temp pankaj$ ls
abc.txt        hi.txt        journaldev.txt    multimove.sh
pankaj:temp pankaj$ ./multimove.sh txt doc
Changing Extension abc.txt --> abc.doc .
Changing Extension hi.txt --> hi.doc .
Changing Extension journaldev.txt --> journaldev.doc .
pankaj:temp pankaj$ ls
abc.doc        hi.doc        journaldev.doc    multimove.sh
pankaj:temp pankaj$

假设:

  • 这些文件只有一个句点(.)
  • 它仅循环遍历当前目录中的所有文件。 但是,可以扩展它以查找子目录中的文件
  • 文件名中存在空格可能会导致脚本出现问题。

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...