についていくつかの質問がありますgrep
。
次のコマンドが '
<Hello
' と一致するのはなぜですか?$ grep -E "\<H" test Hello World <Hello H<ello
「」のみを一致させるにはどうすればよいですか
<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」を検索しますgrep
。grep
次のコマンドは互いにほぼ同じですが、上記のコマンドとは異なります。
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>