首页 > 解决方案 > 终端:通过 MIME 选择 - 需要为每个文件添加扩展名

问题描述

我有大量的旧文件和文件夹,很多没有扩展名。

我结合了 Mac 的 Automator 和这个 shell 代码,成功地打印出给定文件夹中一种文件类型的所有文件路径的列表。

我只是不知道如何将适当的扩展名(例如“.tif”)添加到过滤的文件列表中。

for f in "$@"
do
    find "$f" -type f -exec file --no-pad --mime-type {} + 2>/dev/null \
    | awk '$NF == "image/tiff" {$NF=""; sub(": $", ""); print}'
done

如果我添加:

mv -- "$f" "${f%}.tif"

它只是将“.tif”添加到每个文件和文件夹中。不是过滤列表。

如何仅更改“打印”结果中的文件?

谢谢你提供的所有帮助!:)

标签: macosshellunixterminalautomator

解决方案


您将命令添加到下一行而不是循环块中,这仅适用于所有文件。

对于您当前的逻辑,应将其添加到 awk 的输出中

for f in "$@"
do
    find "$f" -type f -exec file --no-pad --mime-type {} + 2>/dev/null \
    | awk '$NF == "image/tiff" {$NF=""; sub(": $", ""); print}' | xargs -I{} mv {} {}.tif
done 

不过,我不确定这种方法是否非常有效。

由 stellababy 再次编辑:

您可以使用 for 循环以这种方式解决您的问题。

for f in `find . -type f ! -name "*.*"`
do
    file_type=`file -b --mime-type $f`
    if [ "$file_type" = "image/jpeg" ]; then 
        mv $f $f.jpg
    elif [ "$file_type" = "image/png" ]; then 
        mv $f $f.png
    elif [ "$file_type" = "image/tiff" ]; then 
        mv $f $f.tif
    elif [ "$file_type" = "image/vnd.adobe.photoshop" ]; then 
        mv $f $f.psd
    elif [ "$file_type" = "application/pdf" ]; then 
        mv $f $f.pdf
    elif [ "$file_type" = "application/vnd.ms-powerpoint" ]; then 
        mv $f $f.ppt
    elif [ "$file_type" = "application/x-quark-xpress-3" ]; then 
        mv $f $f.qxp
    elif [ "$file_type" = "application/msword" ]; then 
        mv $f $f.doc
    fi
done 

推荐阅读