シェルワンライナー160本ノック問題9
問題9 ログの抽出
問題のファイルは
https://github.com/shellgei/shellgei160
からダウンロードできる。
ログから条件に合う行を抽出する問題だった。最初は
cat log_range.log | awk '/\[24.* 2[123]:/{print $0}/\[25.* 0[012
3]:/'
とやってみたがこれだと3時台の最初のログだけを出すということができない(今回はたまたま3時台のログが1つしかなかったが)。ブログを書くときに気が付いたが awk は2個目のアクションを同じものなら省略できるらしい。気づかずに省略形で書いていた。
$ cat log_range.log | sed -n '/24\/Dec\/2016 21:..:../,/25\/Dec\/2016 03:..:../p'
とやればよい。一つ目の正規表現にマッチした行から二つ目の正規表現にマッチした行までを出力する。
If the second address is a REGEXP, then checking for the ending match
will start with the line _following_ the line which matched the first
address: a range will always span at least two lines (except of course
if the input stream ends).$ seq 10 | sed -n '4,/[0-9]/p'
4
5
info sed でいろいろ見て回ったらちゃんと仕様として書いてあった。