15個のLinux Grepコマンド使用例(実用、常用)
$ cat demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.
例01:指定した文字列を単一ファイルから検索する
コードのコピー
$ grep "this" demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
例02:指定した文字列を複数のファイルから検索する
コードのコピー
$ cp demo_file demo_file1
$ grep "this" demo_* demo_file:this line is the 1st lower case line in this file.demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.
例03:大文字と小文字を無視してgrep-iを使用
コードのコピー
$ grep -i "the" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
And this is the last line.
例04:ファイルに正規表現をマッチさせる
コードのコピー
$ grep "lines.*empty" demo_file
Two lines above this line is empty.
Grepドキュメントから見ると、正規表現は次の一致操作に従う必要があります。
1.? The preceding item is optional and matched at most once.
2.* The preceding item will be matched zero or more times.
3.+ The preceding item will be matched one or more times.
4.{n} The preceding item is matched exactly n times.
5.{n,} The preceding item is matched n or more times.
6.{,m} The preceding item is matched at most m times.
7.{n,m} The preceding item is matched at least n times, but not more than m times.
例05:grep-wで完全一致を検索し、サブ文字列を含まない
コードのコピー
$ grep -i "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.
コードのコピー
$ grep -iw "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.
例06:grep-A,-B,-Cでafter/before/around行を表示する
コードのコピー
$ cat demo_text
4. Vim Word Navigation
You may want to do several navigation in relation to the words, such as:
* e - go to the end of the current word.
* E - go to the end of the current WORD.
* b - go to the previous (before) word.
* B - go to the previous (before) WORD.
* w - go to the next word.
* W - go to the next WORD.