1
0

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 3 years have passed since last update.

grepコマンドをきちんと理解する

Last updated at Posted at 2022-03-03

Linux系のOSでトップレベルに使うコマンドgrep
パイプ「|」と併用で使っているが、逆にそれしか知らない。

grepの細かい使い方を知れば開発が捗りそうなのでここらで理解したい。

基礎

grepはファイルないの文字列を検索するコマンド。

hoge.txt
apple:りんご
pen:ペン
applepen:りんごペン
$ grep <検索ワード> <ファイル名>

$ grep apple hoge.txt
// => ワードに引っかかった行を抜き出す
// apple:りんご
// applepen:りんごペン

パイプ「|」の活用

パイプの左の検索結果をさらに検索

$ grep apple hoge.txt | grep pen
// => applepen:りんごペン

grep以外の出力に対しても使える。
めちゃくちゃ便利。

$ ls | grep hoge
// => hoge.txt

正規表現

もちろん正規表現もいける

// ""必須
$ grep "a.pl.*ペン" hoge.txt
// => applepen:りんごペン

オプション

-n: 行番号付き

$ grep -n apple hoge.txt
// =>
// 1:apple:りんご
// 3:applepen:りんごペン

-i: 大文字・小文字区別なく検索

$ grep -i APPLE hoge.txt
// =>
// apple:りんご
// applepen:りんごペン

-v: 指定したワードを含まない行を検索

$ grep -v apple hoge.txt
// => pen:ペン

--color: 一致した部分をハイライト表示

$ grep --color apple hoge.txt
// => appleが強調される

オプションの組み合わせもできる
-ni --colorで検索するとか良さそう

$ grep -ni --color Apple hoge.txt
// =>
// 1:apple:りんご
// 3:applepen:りんごペン
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?