今回は、Linuxサーバー環境で使える"grep"コマンドについて、紹介します。
$ grep 検索正規表現 ファイル名
人気のスポーツTOP20が書かれている、以下のテキストファイル(test.txt)を使用して、grepコマンド試してみたいと思います。
####################
1st place soccer
2nd place basketball
3rd place cricket
4th place tennis
5th place land
6th place rugby
7th place F1
8th place boxing
9th place ice hockey
10th place volleyball
11th place golf
12th place baseball
13th place American football
14th place mixed martial arts
15th place MotoGP
16th place field hockey
17th place badminton
18th Cycling
19th swimming
20th Snooker / Billiards
####################
$ grep "1st" /tmp/test.txt
このように、検索した文字列がある行の文字列が全て表示されます。
②水泳(swimming)が入っているかどうかを探す場合
$ grep "swimming" /tmp/test.txt
③"place"を検索してみると?
$ grep "place" /tmp/test.txt
"place"と書かれている行の文字列が全て表示されます。
※最初に"plce"と綴りを間違えコマンドを実行していますが、ファイル内に検索した文字列がない場合、何も表示されません。
今までは、基本的な使い方でしたが、最後に、複数条件(and)を用いた場合を紹介します。
④"place"の文字列と"baseball"の文字列を含むものを検索したい場合
$ grep "place" /tmp/test.test.txt | grep "baseball"
"place"だけでやると、全て出ましたが、パイプ[|]で繋ぎ、再度grepコマンドを入力(ファイル名は省略できる)して"baseball"の文字列を含めるという条件を加えると一つしか表示されなくなります。