正确的文件扩展名

akx*_*xer 16 files file-format

我有大约 12000 张不同文件类型的图像,但每一张都被重命名为 *.jpg。

现在我想给他们适当的扩展,我该怎么做

ter*_*don 23

您可以在 bash 中相对轻松地做到这一点:

for f in *jpg; do 
    type=$(file -0 -F" " "$f" | grep -aPo '\0\s*\K\S+') 
    mv "$f" "${f%%.*}.${type,,}"  
done
Run Code Online (Sandbox Code Playgroud)

这与@AB 的答案相同,但使用 shell globs 而不是find. 该${f%%.*}是没有它的扩展名。在-0该的file命令使得它打印\0的文件名,我们再使用后grep的文件类型。这应该适用于任意文件名,包括包含空格、换行符或其他任何内容的文件名。这${type,,}是获得小写扩展名的技巧。它会转换PNGpng.

你没有在你的问题中说,但如果你需要递归并进入子目录,你可以使用它:

shopt -s globstar
for f in **/*jpg; do 
    type=$(file -0 -F" " "$f" | grep -aPo '\0\s*\K\S+') 
    mv "$f" "${f%%.*}.${type,,}"  
done
Run Code Online (Sandbox Code Playgroud)

shopt -s globstar将使bash的globstar选项,它可以让**比赛子目录:

环球之星

如果设置,路径名扩展上下文中使用的模式 ** 将匹配所有文件以及零个或多个目录和子目录。如果模式后跟 /,则仅目录和子目录匹配。


Jac*_*ijm 12

下面的脚本可用于(递归地)将错误设置的扩展名 , 重命名为正确的扩展名.jpg。如果它发现一个不可读的文件,它会在脚本的输出中报告它。

该脚本使用该imghdr模块来识别以下类型:rgb, gif, pbm, pgm, ppm, tiff, rast, xbm, jpeg, bmp, png。有关imghdr模块的更多信息,请点击此处。如链接中所述,该列表可以扩展为更多类型。

事实上,它专门用扩展名重命名文件.jpg,如问题中所述。只需稍作更改,就可以将任何扩展名或一组特定的扩展名重命名为正确的扩展名(或没有扩展名,例如此处)。

剧本:

#!/usr/bin/env python3
import os
import imghdr
import shutil
import sys

directory = sys.argv[1]

for root, dirs, files in os.walk(directory):
    for name in files:
        file = root+"/"+name
        # find files with the (incorrect) extension to rename
        if name.endswith(".jpg"):
            # find the correct extension
            ftype = imghdr.what(file)
            # rename the file
            if ftype != None:
                shutil.move(file, file.replace("jpg",ftype))
            # in case it can't be determined, mention it in the output
            else:
                print("could not determine: "+file)
Run Code Online (Sandbox Code Playgroud)

如何使用

  1. 将脚本复制到一个空文件中,另存为 rename.py
  2. 通过以下命令运行它:

    python3 /path/to/rename.py <directory>
    
    Run Code Online (Sandbox Code Playgroud)