首页 > 解决方案 > 使用 bash 识别文件扩展名并将其附加到文件

问题描述

我有一个包含许多对象的文件夹。这些对象在文件名中没有扩展名。

我想用来file获取 mimetype,然后将对象重命名为object.mimetype.

目前这是我保存为 test.sh 的内容:

#!/bin/bash
for i in *;
do "EXT"==$(file "$i" --mime-type -b | sed 's#.*/##') 
combination= "$i.$EXT"
mv "$i" "$combination"

done

当我在目录上运行 test.sh 时,我得到如下输出:

test.sh: line 3: EXT==tiff: command not found
test.sh: line 4: CCITT_1.: command not found
mv: cannot move 'CCITT_1' to '': No such file or directory
test.sh: line 3: EXT==jpeg: command not found
test.sh: line 4: image.: command not found
mv: cannot move 'image' to '': No such file or directory
test.sh: line 3: EXT==pdf: command not found
test.sh: line 4: Job-Description.pdf.: command not found
mv: cannot move 'Job-Description.pdf' to '': No such file or directory

所以我知道该file ...命令有效,因为我已经对其进行了测试,但是我对其他所有内容都感到困惑。我哪里错了?

标签: bashsedmime-types

解决方案


您可能希望将输出分配$(...)$EXT,因为您必须使用=而不是==,并且不得引用变量名。进行一些其他修改:

#!/bin/bash
for i in *; do
    ext=$(file "$i" --mime-type -b | sed 's#.*/##')
    mv "$i" "$i.$ext"
done

推荐阅读