6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

grep で完全一致させたいときの書き方

Posted at

前提

  • 完全一致で grep させたいときに方法がわからない人向けです。
  • ログ解析とかの時に役立ちそう。

環境

  • macOS High Sierra 10.13.5
  • iTerm2

(※ UNIX コマンドが使える環境なら何でも良さそうだと思います)

TL;DR

$ cat foo.txt | grep -E \s*foobar$
$ cat foo.txt | grep -e \s*foobar$
$ cat foo.txt | egrep \s*foobar$

詳細

grep コマンドには拡張した正規表現を使えるオプションがいくつかあります。

$ man grep
     -E, --extended-regexp
             Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

     -e pattern, --regexp=pattern
             Specify a pattern used during the search of the input: an input line is selected if it matches any of the
             specified patterns.  This option is most useful when multiple -e options are used to specify multiple pat-
             terns, or when a pattern begins with a dash (`-').

最初は行頭かつ行末という条件の正規表現を書こうと思ったんですが、それだと行頭のインデントやスペースなどを考慮してくれなくなるので、0個以上のスペースという条件にしました。

$ cat foo.txt | grep -E ^"foobar"$
じゃなくて
$ cat foo.txt | grep -E "\s*foobar"$

でもこれで言うと、一致する部分って行頭のスペースすべて含まれてしまうんですよね。ログファイルの解析したい時って、一致部分をハイライトしたいことわりとあると思うんですけど、これだとむしろ見にくくなったりするのかな…。

参考文献

6
3
1

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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?