他のコマンドと一緒に使用するときに複数の文字列を特定する方法は?

他のコマンドと一緒に使用するときに複数の文字列を特定する方法は?

次の方法を理解しようとしています。

grep -i

別のコマンドでgrepを使用した後、複数の文字列を使用します。たとえば、

last | grep -i abc
last | grep -i uyx

上記を1つのコマンドにまとめたいのですが、インターネットで検索すると、grepがコマンド以外のファイルで使用されているときにgrepで複数の文字列を使用する方法への参照のみを見つけることができます。私は次のことを試しました:

last | grep -i (abc|uyx)

または

last | grep -i 'abc|uyx'

しかし、これはうまくいきません。目的の結果を得るための正しい構文は何ですか?

よろしくお願いします。

ベストアンサー1

grep標準オプションから始めて、さまざまなオプションを個別に使用できます。

grep -i -e abc -e uyx
grep -i 'abc
uyx'
grep -i -E 'abc|uyx'

一部のgrep実装では、次のこともできます。

grep -i -P 'abc|uyx' # perl-like regexps, sometimes also with
                     # --perl-regexp or -X perl
grep -i -X 'abc|uyx' # augmented regexps (with ast-open grep) also with
                     # --augmented-regexp
grep -i -K 'abc|uyx' # ksh regexps (with ast-open grep) also with
                     # --ksh-regexp
grep -i 'abc\|uyx'   # with the \| extension to basic regexps supported by
                     # some grep implementations. BREs are the
                     # default but with some grep implementations, you
                     # can make it explicit with -G, --basic-regexp or
                     # -X basic

(...)周りに s を追加できますがabc|uyx\(...\)BRE の場合)必須ではありません。 s()sなどもシェル言語の構文では特殊文字なので、文字通り渡すには引用|符を囲む必要があります。grep

grep一部の実装(非標準)では、正規表現構文の一部として大文字と小文字を区別しない一致を有効にすることもできます。

grep -P '(?i)abc|uyx' # wherever -P / --perl-regexp / -X perl is supported
grep -K '~(i)abc|uyx' # ast-open grep only
grep -E '(?i)abc|uyx' # ast-open grep only
grep '\(?i\)abc|uyx'  # ast-open grep only which makes it non-POSIX-compliant

これは標準オプション-iと比較して実際に大きな利点を提供しません。たとえば、abc大文字と小文字を区別せずに大文字と小文字を区別して一致させたい場合(より興味深い場合)、uyx次のことができます。

grep -P 'abc|(?i)uyx'

または:

grep -P 'abc|(?i:uyx)'

(および正規表現構文の他の同等の変形)。

同等の標準は次のとおりです。

grep -e abc -e '[uU][yY][xX]'

(大文字と小文字を区別しない一致は、通常、ロケールによって異なります。たとえば、大文字かロケールによって異なりますi)。Iİgrep -i i

おすすめ記事