LoginSignup
10

More than 3 years have passed since last update.

macOS の find コマンドで正規表現を使い、複数の拡張子を検索する

Last updated at Posted at 2017-10-26

TL;DR

$ find -E . -type f -iregex ".*\.(png|jpg|jpeg)" 

経緯

とりあえずググって調べると...

-name と -or を使う方法を発見する。

$ find . -type f \( -name "*.png" -or -name "*.jpg" -or -name "*.jpeg" -name "*.PNG" -or -name "*.JPG" -or -name "*.JPEG" \)

大文字、小文字を区別するので記述が長い。かなりイマイチ。

-iname を発見する。

$ find . -type f \( -iname "*.png" -or -iname "*.jpg" -or -iname "*.jpeg" \)

大文字、小文字を区別しないので記述が少し短くなった。

正規表現を発見する。 しかし ERROR になる。

$ find . -type f -regex ".*\.(png|jpg|jpeg|PNG|JPG|JPEG)"


$ man find で -E オプションを発見する。

-E Interpret regular expressions followed by -regex and -iregex primaries as extended (modern) regular expressions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both formats.

直訳すると

-E 基本的な正規表現 (BRE) ではなく、-regex と -iregex のプライマリに続く正規表現を、拡張された (現代的な) 正規表現として解釈します。re_format(7) のマニュアルページでは、両方のフォーマットについて完全に説明しています。


-E オプションで成功した。

$ find -E . -type f -regex ".*\.(png|jpg|jpeg|PNG|JPG|JPEG)"

大文字、小文字を区別するので記述が長い。

-iregex で記述すると大文字、小文字を区別しない。

$ find -E . -type f -iregex ".*\.(png|jpg|jpeg)"

これが最短か?

オマケ

$ find -E . -type f -iregex ".*.(png|jpg|jpeg)"

これでも動く。

これは動かない。

$ find -E . -type f -iregex "*.(png|jpg|jpeg)"

参考:findの正規表現は完全一致で

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10