各単語の先頭にある特殊文字と一致するようにgrepに指示する方法

各単語の先頭にある特殊文字と一致するようにgrepに指示する方法

についていくつかの質問がありますgrep

  1. 次のコマンドが ' <Hello' と一致するのはなぜですか?

    $ grep -E "\<H" test
    Hello World
    <Hello
    H<ello
    
  2. 「」のみを一致させるにはどうすればよいですか<Hello

ベストアンサー1

grep文字列(正規表現)の特別な解釈を避けるには-F(または--fixed-string)を使用します。

$ cat test
one < two
Hello World
X<H
A <H A
I said: <Hello>
$ grep -F '<H' test
X<H
A <H A
I said: <Hello>

検索パターンを正しく引用する必要があることに注意してください。そうしないと、シェルはそれを誤って解釈する可能性があります。たとえば、grep -F <H test代わりに実行すると、シェルは「H」というファイルを開き、それを使用して文字列「test」を検索しますgrepgrep次のコマンドは互いにほぼ同じですが、上記のコマンドとは異なります。

 grep -F <H test
 grep -F test <H         # location of `<H` does not matter
 grep -F H test
 cat H | grep -F test    # useless cat award

単語だけが一致する場合は、マンページを確認してくださいgrep(1)

   -w, --word-regexp
          Select  only those lines containing matches that form whole words.  The
          test is that the matching substring must either be at the beginning  of
          the  line, or preceded by a non-word constituent character.  Similarly,
          it must be either at the end of the line  or  followed  by  a  non-word
          constituent   character.    Word-constituent  characters  are  letters,
          digits, and the underscore.

使用例(上記のテストファイルを使用):

$ grep -F -w '<H' test
A <H A

-Fここでは<H特別な意味がないのでオプションですが、このリテラルモードを拡張したい場合に便利です。)

単語の先頭を一致させるには正規表現が必要です。

$ grep -w '<H.*' test    # match words starting with `<H` followed by anything
A <H A
I said: <Hello>

おすすめ記事