微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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$

假设:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐