Filenames

給定一個 mime-type 獲取相應的文件副檔名

  • August 25, 2015

我想將文件下載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 類型和文件副檔名之間沒有一對一的映射,但它應該處理正常的文件副檔名。

與 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

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}"

引用自:https://unix.stackexchange.com/questions/86349