0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Linux】grepコマンドの基本的な使い方

Posted at

前提

以下のファイルがある前提とします。

  • sample_1.txt
  • sample_2.txt
hello
world
Hello, World!

※どちらのファイルも内容は同じです。


特定の文字列を含む行を検索

入力

$ grep "Hello" sample_1.txt

sample_1.txt の中から "Hello" を含む行を検索します。

出力

Hello, World!

大文字小文字を無視する -i

入力

$ grep -i "Hello" sample_1.txt

sample_1.txt の中から "Hello" を含む行を、大文字小文字を区別せずに検索します。

出力

hello
Hello, World!

行番号を表示する -n

入力

$ grep -n "Hello" sample_1.txt

sample_1.txt の中から "Hello" を含む行を検索し、行番号を付けて表示します。

出力

3:Hello, World!

複数パターンを検索 -E

入力

$ grep -E "hello|world" sample_1.txt

sample_1.txt の中から "hello" または "world" を含む行を検索します。
-E オプションを使用すると、拡張正規表現を利用できます。

出力

hello
world

前後の行を表示する -C

入力

$ grep -C1 "world" sample_1.txt

sample_1.txt の中から "world" を含む行と、その前後1行を検索します。

出力

hello
world
Hello, World!

特定の拡張子のファイルを対象として検索

入力

$ grep "Hello" *.txt

拡張子が .txt のファイルを対象として、"Hello" を含む行を検索します。

出力

sample_1.txt:Hello, World!
sample_2.txt:Hello, World!

検索にヒットしたファイル名のみ表示 -l

入力

$ grep -l "Hello" *.txt

拡張子が .txt のファイルを対象として、"Hello" を含むファイルの名前のみを表示します。

出力

sample_1.txt
sample_2.txt

ディレクトリを指定して再帰的に検索 -r

入力

$ grep -r "Hello" .

カレントディレクトリ (.) 以下のすべてのファイルを再帰的に検索し、"Hello" を含む行を表示します。

出力

./sample_1.txt:Hello, World!
./sample_2.txt:Hello, World!
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?