1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Linux】grepコマンドの使い方

Posted at

基本的な使い方

grepコマンドは標準入力や指定したファイルから特定の文字列が含まれている行を取得できます。

sample.txtを作成します。

sample.txt
12345
67890
ABCDE
FGHIJ
123
678
ABC
FGH

grepコマンドを以下のように実行します。

$ grep '1' sample.txt
12345
123

標準入力を対象に実行する場合には以下のようにします。

$ cat sample.txt | grep '1'
12345
123

AND検索

複数の文字列を含む行を取得するには以下のように実行します。

$ grep '1' sample.txt | grep '5'
12345

15の両方が含まれる行のみ取得できています。

OR検索

複数の文字列のいずれかが含まれている行を取得するには以下のように実行します。

$ grep -e '1' -e 'D' sample.txt
12345
ABCDE
123

または正規表現を使用して以下のように実行します。

$ grep -E '1|D' sample.txt
12345
ABCDE
123

上記どちらの方法でも1またはDを含んだ行を取得できています。

NOT検索

特定の文字列を含まない行を取得するには以下のように実行します。

$ grep -v 'A' sample.txt
12345
67890
FGHIJ
123
678
FGH

Aを含まない行を取得できています。

完全一致

特定の文字列に完全一致する行を取得する場合には以下のように実行します。

$ grep -x 'ABC' sample.txt
ABC

ABCに完全一致する行のみ取得できています。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?