Linuxの世界では、 G エネルギッシュなR egular E xpression P arserまたはgrepは、すべてのLinux管理者が使用する最も強力なコマンドの1つです。これを使用すると、ファイルの内容を検索したり、コマンド出力内で検索を実行したりできるはずです。それだけでなく、このチュートリアルで説明するその他の多くのことも実行できます。
例を使用したGREPコマンドの使用法
このガイドでは、コマンドの使用法を説明し、時間を大幅に節約できる便利で便利な例をいくつか紹介します。このチュートリアルはUbuntuマシンで実行されますが、コマンドはすべてのLinuxディストリビューションで機能します。
インストール
コマンドの使用を開始するには、最初に、コマンドがシステムにすでにインストールされているかどうかを確認する必要があります。インストールされていない場合は、ターミナルで次のコマンドを実行します。
sudo apt install grep
コマンドのバージョンをチェックして、正常にインストールされていることを確認できます。
grep --version

構文
grep [option/s] [pattern] [file]
[option / s]の場所:
- -i –>大文字と小文字の区別に関係なく検索パターンを確認するために使用されます。
- -c –>プレビュー、一致するパターンの数。
- -v –>指定されたパターンを含まない一致しない行を選択します。
- -n –>行番号をプレビューします。
ここで、[pattern]は正規表現であり、[file]はそのコンテンツで検索するファイルです。
例
ケースシナリオの例で使用するテストファイルを作成します。
vi grep_tuts

grep_tutsファイルに次の行を貼り付けます。
Hi Guys, i am hend. And this is a tutorial file for the usage of the grep commad. The next 2 lines are empty lines. Hope You Will Enjoy This Tutorial. Bye.

例1.1つのファイルで文字列を検索するには。
grep "hend" grep_tuts

例2.後で使用するgrep_tutsファイルからコピーを作成しましょう。
cp grep_tuts grep_tuts2

複数のファイルで特定の文字列を検索するには、次のコマンドを使用します。
grep "hend" grep_tuts grep_tuts2

例3.大文字と小文字を区別せずにファイル内の特定の文字列を検索するには。
grep -i "tutorial" grep_tuts

例4.大文字と小文字の区別に関係なく、ファイル内の特定のパターンを検索するには。
grep -i "the.*lines" grep_tuts
これは、「the」文字列で始まり「lines」で終わる行を検索することを意味します。 *は0個以上の文字を示し、-iオプションは「the」と「lines」の大文字小文字を無視します。

ただし、-iオプションを使用しなかった場合、結果は得られません。
grep "the.*lines" grep_tuts

例5.検索しているパターンの後に2行を表示するには。
grep -A 2 "hend" grep_tuts

例6.検索しているパターンの前に1行を表示するには。
grep -B 1 "hend" grep_tuts

例7.検索しているパターンの周囲(または前後)に1行を表示するには。
grep -C 1 "hend" grep_tuts

例8.現在のディレクトリに存在するすべてのファイルで特定の文字列を検索するには。
grep -r "Enjoy" *

例9.指定された文字列を含まないすべての行を表示するには。
grep -v -i -e "Enjoy" grep_tuts

例10.検索している文字列を含むすべての行の数を表示するには。
grep -c "this" grep_tuts

例11.大文字と小文字の区別に関係なく、検索する文字列を含むすべての行の数を表示するには。
grep -c -i "this" grep_tuts

例12.一致しないパターンの数を表示するには。
grep -v -c "this" grep_tuts

例13.検索している文字列を含むすべてのファイル名を表示するには。
grep -l "this" *

例14.行数を表示するには。
grep -n "this" grep_tuts

例15.特定のコマンドの出力を検索します。たとえば、「tuts」ユーザーによって開始された実行中のすべてのプロセスを一覧表示します。
ps aux | grep tuts

Linuxでのgrepコマンドの使用については以上です。