概要
LPICレベル1勉強ついでにgrepコマンドのオプションについて
マニュアル(man)を読み解く
環境
macOS High Sierra(バージョン 10.13.14)
マニュアルの参照の仕方
man 1 grep
manでコマンドについてのマニュアルを参照するときは1を指定する
オプション一覧
- その1: -A、-B
マニュアル
-A num, --after-context=num
Print num lines of trailing context after each match. See also
the -B and -C options.
-B num, --before-context=num
Print num lines of leading context before each match. See also
the -A and -C options
マッチしてから行の前後を表示したい場合には-A、-Bが使える。
-Aではマッチしてから前何行、-Bではマッチしてから後何行を指定
例
$ cat example.txt
ABC
DEF
GHI
JKL
MNO
$ cat example.txt | grep -A 1 -B 1 "GHI"
DEF
GHI
JKL
- その2: -E、-F
マニュアル
-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).
正規表現を使いたいときは-E、
?とか$とか特殊な文字を含む文字列をそのままの文字列として検索したいときは-Fが使える。
個人的には-Fを最近知ったので目から鱗だった
例
$ cat example2.txt
ABC
DEF
GHI
JKL
.KL$
MNO
$ grep -E ".KL$" example2.txt
JKL
$ grep -F ".KL$" example2.txt
.KL$
- その3: -f
マニュアル
-f file, --file=file
Read one or more newline separated patterns from file. Empty pattern lines match every input line. Newlines are not considered part of a pattern. If file is empty, nothing is matched.
検索の条件が大量にある場合など、検索条件を別ファイルから入力させる必要がある場合は
-fが使える。
例
$ cat search.txt
EF
G
$ cat example3.txt
ABC
DEF
GHI
JKL
.KL$
MNO
$ grep -f search.txt example3.txt
DEF
GHI
以下追記中、、、!