我需要找到所有的图像文件从目录(gif, png, jpg, jpeg)。

find /path/to/ -name "*.jpg" > log

如何修改这个字符串,不仅找到。jpg文件?


find /path/to/  \( -iname '*.gif' -o -iname '*.jpg' \) -print0

将工作。也许有更优雅的方式。


find /path -type f \( -iname "*.jpg" -o -name "*.jpeg" -o -iname "*gif" \)

find /path/to/ -type f -print0 | xargs -0 file | grep -i image

它使用file命令来尝试识别文件的类型,而不管文件名(或扩展名)。

如果/path/to或文件名包含字符串image,则上述操作可能返回虚假命中。那样的话,我建议

cd /path/to
find . -type f -print0 | xargs -0 file --mime-type | grep -i image/

find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

find -E /path/to -regex ".*\.(jpg|gif|png|jpeg)">日志

-E使您不必转义正则表达式中的paren和管道。


find -regex ".*\.\(jpg\|gif\|png\|jpeg\)"

作为上面@Dennis Williamson回答的补充,如果你想让同一个regex对文件扩展名不区分大小写,使用-iregex:

find /path/to -iregex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

在Mac OS上使用

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

如果文件没有扩展名,我们可以寻找文件mime类型

find . -type f -exec file -i {} + | awk -F': +' '{ if ($2 ~ /audio|video|matroska|mpeg/) print $1 }'

哪里(音频|视频|matroska|mpeg)是mime类型正则表达式

&如果你想删除它们:

find . -type f -exec file -i {} + | awk -F': +' '{ if ($2 ~ /audio|video|matroska|mpeg/) print $1 }' | while read f ; do
  rm "$f"
done

或者删除除了这些扩展名以外的所有内容:

find . -type f -exec file -i {} + | awk -F': +' '{ if ($2 !~ /audio|video|matroska|mpeg/) print $1 }' | while read f ; do
  rm "$f"
done

注意!~而不是~


添加-regextype posix-extended选项只在我的情况下有效:

sudo find . -regextype posix-extended -regex ".*\.(css|js|jpg|jpeg|png|ico|ttf|woff|svg)" -exec chmod 0640 {} \;