如何使用脚本重命名文件/基于mimetype更改其扩展名?

我希望有人可以向我解释如何更改文件类型。 我最近将我的照片上传到我的笔记本电脑上,其中一半是作为文件保存而不是图像,这意味着我无法将它们上传到网站上进行打印。

我正在寻找一步一步的过程,如果我可以同时完成所有这些过程或者让它们单独完成。 我有500多个要改变。

你应该能够使用mimetype实用程序 – 来自man mimetype

 NAME mimetype - Determine file type SYNOPSIS mimetype [options] [-] files DESCRIPTION This script tries to determine the mime type of a file using the Shared MIME-info database. It is intended as a kind of file(1) work-alike, but uses mimetypes instead of descriptions. 

例如:

 $ mimetype somefile somefile: image/jpeg 

但是,默认情况下, mimetype将“相信”扩展名(如果存在) – 所以:

 $ cp somefile somefile.gif $ mimetype somefile.gif somefile.gif: image/gif 

您可以通过添加-M开关告诉它仅使用文件的魔术字节来进行确定:

 $ mimetype -M somefile.gif somefile.gif: image/jpeg 

你可以添加-bbrief说明:

 $ mimetype -bM somefile.gif image/jpeg 

如果你想编写重命名脚本 ,我会建议这样的事情:

 #!/bin/bash while read -r -d '' f; do mt="$(mimetype -bM "$f")" ext="${mt##*/}" case "$ext" in jpeg|gif|png) echo mv -v "$f" "$f.$ext" ;; *) echo "skipping mimetype $mt... " ;; esac done < <(find -type f -print0) 

笔记:

  1. 它实际上并没有按照所写的重命名: echo mv只是输出它做的事情 - 请检查并在删除echo之前仔细检查它是否在文件上按预期运行
  2. 它只对jpeggifpng文件进行操作:如果有其他图像类型,则需要明确添加
  3. 它会根据魔术字节重命名(添加一个额外的扩展名)它认为具有错误扩展名的任何文件

使用像exiftool这样的工具可能还有其他更容易的选择