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.

sedを実践的に使う

Last updated at Posted at 2021-12-14

概要

sedを使っていろんな場面を想定して、例題を交えて書いていこうと思います
記事も少しずつ付け加えていく予定です

使い方例

logから特定の文字を抜き出す

想定 10-1.log.7.gzなどを検索して、200を含むかつaaaのパラメータの値を取得したいと思います

grep結果がこんな感じだとします

10-1.log.7.gz:2021-12-10T22:51:20+09:00{message:200.201.111.222 - - [10/Dec/2021:13:51:20 +0000] \"GET /show/data.html?aaa=11345&bbb=4577&ccc=5&dd=hoirjl56na HTTP/1.1\" 200 2 \"-\" \"-\" \"-\" \"1.061\" \"-\" \"-\"}

順番がしっかりしていれば以下でとれますが

zgrep "message" 10-* | grep " 200 " | awk -F'[=& ]' '{print $8}'

aaaがどこにあるかわからないので正規表現で取得したいと思います

 zgrep "message" 10-* | grep " 200 " | sed -e "s/^.*aaa=\([^&]*\)\&.*$/\1/"

結果:11345が取れます

point

  • \( \) で囲まれた部分が抜き出せます
  • \1を置き換え文字部分に設定すると上記で括弧に囲まれた部分が抽出できます
  • [^&]この部分ですが、一番初めに&を出現する以外の全てとなるためaaaの値を取ることができるようになります

参考

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?