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

grep コマンド Linux

Last updated at Posted at 2024-01-26

ファイルを開いた中身に、「検索したい文字列」が含まれているファイルのリストを表示(検索対象フォルダ配下を再帰検索)

grep [検索したい文字列] -rl [検索対象フォルダのパス]

前後の行も取得して出力したいとき(-数字 / -B 数字 / -A 数字)

サンプル:前後の行も取得+複数の検索対象
# 検索対象(plug & exact)の前後3行を表示
cat /etc/yum.conf | grep -3 -e plug -e exact

# 検索対象(plug & exact)の前4行も表示(Back)
cat /etc/yum.conf | grep -B 4 -e plug -e exact

# 検索対象(plug & exact)の後5行も表示(Add)
cat /etc/yum.conf | grep -A 5 -e plug -e exact

他のコマンドと組み合わせず、 grep だけで良ければ cat は不要

grep -3 -e plug -e exact /etc/yum.conf

-を検索対象文字列として認識させたいときの記述例

--を使うか
grep -- '-word'
-をエスケープする
grep - '\-word'

-- についてのChatGPT説明

-- は、コマンドラインオプションの終了を示すために使われます。
これ以降のすべての文字列はオプションではなく、引数として扱われます。
これにより、検索パターンやファイル名が - で始まる場合でも正しく解釈されます。
この場合、--word をオプションではなくパターンとして扱うことを保証します。

参考と過去記事

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