在 Linux 中递归修复图像文件扩展名

Bla*_*iwi 5 linux script bash images

我有一堆来自错误命名的扫描/传真的图像文件,我需要为我们的 Linux 用户修复。事实证明,我们有一堆扫描件是 PNG 文件,这些文件被标记为 *.jpg,反之亦然。在 Windows 下,这从来都不是问题,因为资源管理器/Office 只会忽略扩展名。但是在 Linux 下,Eye of GNOME 等最终只是拒绝打开文件,因为内容与扩展名不匹配。

有没有人对可以做到这一点的工具或一小段脚本有任何建议?我可以编写一个 C 程序来做到这一点,但这似乎有点矫枉过正。只是坐下来手动手动重命名不是一种选择,有数千种。

编辑:我看到该file命令将查看文件的实际内容并显示它是什么。我不太确定如何使用它的信息。

gle*_*man 9

您需要遍历看起来像图像文件的文件,调用file以查看它们的真实内容,然后适当地重命名它们

for f in *.{jpg,JPG,png,PNG,jpeg,JPEG}; do 
    type=$( file "$f" | grep -oP '\w+(?= image data)' )
    case $type in  
        PNG)  newext=png ;; 
        JPEG) newext=jpg ;; 
        *)    echo "??? what is this: $f"; continue ;; 
    esac
    ext=${f##*.}   # remove everything up to and including the last dot
    if [[ $ext != $newext ]]; then
        # remove "echo" if you're satisfied it's working
        echo mv "$f" "${f%.*}.$newext"
    fi
done
Run Code Online (Sandbox Code Playgroud)