grep, egrep, fgrep の違い

grepは、条件を指定して文字列を検索できるコマンド。似たようなコマンドとして、egrepfgrepが存在する。
簡単に違いについて調べてみたので備忘録的に書いておく。

環境

% sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.3
BuildVersion:   19D76

% grep --version
grep (BSD grep) 2.5.1-FreeBSD
% fgrep --version
fgrep (BSD grep) 2.5.1-FreeBSD
% egrep --version
egrep (BSD grep) 2.5.1-FreeBSD

grepとは

指定したパターンを含む文字列をファイルから検索するコマンド。検索結果は行ごとに表示される。基本的にはgrep <検索するパターン> <ファイル名>の形式で実行する。
例として、以下のsample.txtを対象として検索を行なってみる。

% cat sample.txt
abc
ABC
123
^123
% grep '1' sample.txt
123
^123

正規表現も使うことができる。例えば、「1から始まる文字列」を検索したい場合は、以下のように指定できる。

% grep '^1' sample.txt 
123

egrepとは

検索するパターンに拡張正規表現が使える。例えば、「1もしくはaから始まる文字列」を検索したい場合は、以下のように指定できる。

% egrep '^(1|a)' sample.txt
abc
123

grepコマンドでも、-Eオプションでパターンを指定することで、同じように検索ができる。

% grep '^(1|a)' sample.txt

% grep -E '^(1|a)' sample.txt
abc
123

fgrepとは

入力された文字列をそのまま検索できる。例えば、正規表現にあたる文字列をそのまま検索したいときに使える。

% fgrep '^1' sample.txt 
^123
% fgrep '^(1|a)' sample.txt 

grepコマンドでも、-Fオプションでパターンを指定することで、同じように検索ができる。

% grep '^1' sample.txt 
123
% grep -F '^1' sample.txt 
^123

まとめ

egrep拡張正規表現が使える。fgrepは入力された文字列をそのまま検索できる。
grepでもオプションをつけることで、同じような条件で検索ができる。

egrep = grep -E
fgrep = grep -F

man grepgrepのマニュアルを見てみると、同じように動作すると書かれていることが確認できる。

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

     -F, --fixed-strings
             Interpret pattern as a set of fixed strings (i.e. force grep to behave as fgrep).

GNU Grep 3.5 の記述を確認すると、以下のような記載が確認できる。
(2.4 grep Programs より引用)

In addition, two variant programs egrep and fgrep are available. egrep is the same as grep -E. fgrep is the same as grep -F. Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified.

egrepとfgrepは後方互換性の維持のため(古いプログラムを改修する必要がないよう)に残されているとのこと。普段使う分には、grepコマンドにオプションを指定して使えばよさそう。