2
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コマンドの基本(検索の王様!初心者向け解説)

2
Posted at

【Linux入門】grepコマンドの基本(検索の王様!初心者向け解説)

はじめに

Linuxを勉強していて、ファイルの中から「特定の文字を探したいな〜」って思うことありませんか?
そんなときに大活躍するのが grep コマンド です。

私は最初、grep を知ってから「え、もう探すの一瞬じゃん!」ってちょっと感動しました。
この記事では、初心者でもすぐに使える基本の grep の使い方をまとめます。


基本の使い方

grep "word" file.txt

サンプル出力(file.txt の中身に "hello" を探した場合):

hello world
this is hello linux

ファイルの中で一致した行だけを表示してくれます。
シンプルだけど強力!


大文字・小文字を区別しない(-i)

grep -i "hello" file.txt

サンプル出力:

Hello World
hello world
HELLO WORLD

-i をつけると大文字・小文字を無視して検索できます。
「HELLO」でも「hello」でも全部見つけてくれるので安心です。


行番号を表示(-n)

grep -n "hello" file.txt

サンプル出力:

2:hello world
5:this is hello linux

「どの行にあったのか?」がわかるように行番号をつけて表示してくれます。
エラー調査のときにめちゃくちゃ便利です。


ディレクトリごと検索(-r)

grep -r "main" ./project

サンプル出力:

./project/app.c:12:int main() {
./project/test.c:8:void test_main() {

ディレクトリの中をまとめて検索できます。
プログラムや設定ファイルを探すときはだいたいこれを使ってます。


検索結果をわかりやすく色付きに(--color)

grep --color "hello" file.txt

サンプル出力(イメージ):

this is [hello] linux

実際のターミナルでは [hello] 部分が色付きで強調されます。
「パッと見でどこにあるかわかる」のが本当に助かる〜。


まとめ

  • grep "word" file.txt でテキストを検索
  • -i で大文字小文字を無視、-n で行番号表示
  • -r でディレクトリごと検索、--color で見やすく

grep は検索の王様みたいなコマンドです。
最初は grep "単語" ファイル名 だけでも十分役立ちます。

私もよく「grep で探す → less で読む」って流れで使ってます。
慣れてくるとこれなしでは生きられなくなります…笑


次はファイル権限でつまずきがちな chmod をやってみようかな✍️


💡 ちなみに…
ほかにも「Linux初心者におすすめの学習リソース」をまとめた記事を書いてます。

👉 Linux初心者におすすめの学習リソースまとめ

リソース選びで迷ったときの参考になると思うので、良かったらのぞいてみてくださいね〜。

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