LoginSignup
23
17

More than 5 years have passed since last update.

Linuxのgrep(指定文字検索)で該当行の行番号のみ出力する

Last updated at Posted at 2015-05-26

検索対象ファイルの内容で検索したい文字を含む行の行番号のみを取得する

grep -e "検索文字列" -n 検索対象ファイル名 | sed -e 's/:.*//g'

★検索対象ファイルの中から検索文字列を含む行を取得した後、その検索結果をパイプに通し、「行番号:該当行内容」となっている出力結果をsedコマンドを使用し「:」以降の文字列を空白に全置換することにより行番号のみを取得することができる

以下のquerylog.txtの中から「DELETE」を含む行の行番号のみを取得する

image1.GIF

grep -e "DELETE" -n querylog.txt を実行した時の出力結果。
(8行目と11行目に「DELETE」を含む文字列があるとわかる)

image2.GIF

「でも、欲しいのは行番号だけなんだけど(´・ω・`)」ということありませんか??

とりあえず私はありました。( ´_ゝ`)←

なので、パイプを利用して行番号だけ出力するように以下コマンドを実行。

grep -e "DELETE" -n querylog.txt | sed -e 's/:.*//g'

image3.GIF

できました♪ヽ(^^)ノ

23
17
2

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
23
17