【发布时间】:2011-02-06 23:15:24
【问题描述】:
我需要从目录中找到所有图像文件(gif、png、jpg、jpeg)。
find /path/to/ -name "*.jpg" > log
如何修改此字符串以不仅查找 .jpg 文件?
【问题讨论】:
我需要从目录中找到所有图像文件(gif、png、jpg、jpeg)。
find /path/to/ -name "*.jpg" > log
如何修改此字符串以不仅查找 .jpg 文件?
【问题讨论】:
find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log
【讨论】:
find /path/to/ \( -iname '*.gif' -o -iname '*.jpg' \) -print0
会起作用。可能有更优雅的方式。
【讨论】:
find /path/to/ \( -iname '*.gif' -o -iname '*.jpg' \) -exec ls -l {} \; 否则 exec 仅适用于最后一部分(在这种情况下为 -iname '*.jpg' )。
find /path/to/ -iname '*.gif' -o -iname '*.jpg' -print0 只会打印 jpg 文件!这里需要括号:find /path/to/ \( -iname '*.gif' -o -iname '*.jpg' \) -print0
find -E /path/to -regex ".*\.(jpg|gif|png|jpeg)" > log
-E 使您不必逃避正则表达式中的括号和管道。
【讨论】:
-E 选项告诉find 使用“扩展正则表达式”。其他几个工具也有类似的选项,但我不确定这个选项是否适用于所有 UNIX 发行版。
find . -regextype posix-extended -regex ".*\.(jpg|gif|png|jpeg)"。
find -E /path/to -iregex ".*\.(jpg|gif|png|jpeg)" > log。使用-iregex 标志告诉find 不区分大小写。
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 -type f \( -iname "*.jpg" -o -name "*.jpeg" -o -iname "*gif" \)
【讨论】:
-iname *.jpg、-o -name *.jpeg、-o -iname *gif 的格式都略有不同。
在 Mac OS 上使用
find -E packages -regex ".*\.(jpg|gif|png|jpeg)"
【讨论】:
作为对@Dennis Williamson 上述回复的补充,如果您希望相同的正则表达式对文件扩展名不区分大小写,请使用 -iregex :
find /path/to -iregex ".*\.\(jpg\|gif\|png\|jpeg\)" > log
【讨论】:
find -regex ".*\.\(jpg\|gif\|png\|jpeg\)"
【讨论】:
如果文件没有扩展名,我们可以查找文件 mime 类型
find . -type f -exec file -i {} + | awk -F': +' '{ if ($2 ~ /audio|video|matroska|mpeg/) print $1 }'
其中 (audio|video|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 {} \;
【讨论】: