给定一个 mime-type 获取相应的文件扩展名

给定一个 mime-type 获取相应的文件扩展名

我想将文件下载到具有curl适当扩展名的临时目录中。

目前我做这样的事情:

tmp="$(mktemp -t 'curl')"
curl -o "$tmp" http://example.com/generate_image.php?id=44
file -b --mime-type "$tmp"

这将打印下载文件的 mime 类型,但我如何将它们映射到扩展名?

正如你所看到的,我不能只提取 url 的“扩展名”,因为这会给出.php而不是.png.

我知道 mime 类型和文件扩展名之间没有一对一的映射,但它应该处理正常的文件扩展名。

答案1

与 Windows 不同,Unix 通常没有file extensions.但是您可以使用该/etc/mime.types文件来提供这些翻译:

image/jpeg: jpg
image/gif: gif
image/png: png
image/x-portable-pixmap: ppm
image/tiff: tif

然后通过扩展名进行匹配:

$ ext=$(grep "$(file -b --mime-type file.png)" /etc/mime.types | awk '{print $2}')

$ echo $ext
png

答案2

Bash 脚本采用一个参数 - 文件名,并尝试使用 file 命令和系统 mime.types 文件根据其 mime 类型对其进行重命名:

#!/bin/bash

# Set the location of your mime-types file here.  On some OS X installations,
# you may find such a file at /etc/apache2/mime.types; On some linux distros, 
# it can be found at /etc/mime.types
MIMETYPE_FILE="/etc/apache2/mime.types"

THIS_SCRIPT=`basename "$0"`
TARGET_FILE="$1"
TARGET_FILE_BASE=$(basename "$TARGET_FILE")
TARGET_FILE_EXTENSION="${TARGET_FILE_BASE##*.}"
if [[ "$TARGET_FILE_BASE" == "$TARGET_FILE_EXTENSION" ]]; then
    # This fixes the case where the target file has no extension
    TARGET_FILE_EXTENSION=''
fi
TARGET_FILE_NAME="${TARGET_FILE_BASE%.*}"


if [ ! -f "$MIMETYPE_FILE" ]; then
    echo Could not find the mime.types file.  Please set the MIMETYPE_FILE variable in this script.
    exit 1
fi

if [ "$TARGET_FILE" == "" ]; then
    echo "No file name given. Usage: ${THIS_SCRIPT} <filename>"
    exit 2
fi

if [ ! -f "$TARGET_FILE" ]; then
    echo "Could not find specified file, $TARGET_FILE"
    exit 3
fi

MIME=`file -b --mime-type $TARGET_FILE`
if [[ "${MIME}" == "" ]]; then
    echo ${THIS_SCRIPT} $TARGET_FILE - Could not find MIME-type.
    exit 4
fi

EXT=$(grep "${MIME}" "${MIMETYPE_FILE}" | sed '/^#/ d' | grep -m 1 "${MIME}" | awk '{print $2}')

if [[ "$EXT" == "" ]]; then
    echo ${THIS_SCRIPT} ${TARGET_FILE} - Could not find extension for MIME-Type ${MIME}
    exit 5
fi


if [ "${TARGET_FILE_EXTENSION}" == "${EXT}" ]; then
    echo ${TARGET_FILE} already has extension appropriate for MIME-Type ${MIME}
    exit 0
fi

echo Renaming "${TARGET_FILE}" to "${TARGET_FILE}.${EXT}"
mv "${TARGET_FILE}" "${TARGET_FILE}.${EXT}"

相关内容