@kyanny's blog

My thoughts, my life. Views/opinions are my own.

awk: ある行から別のある行までの範囲を抽出する

カンマ区切りでパターンを二つ並べると、一つ目のパターンにマッチする行から二つ目のパターンにマッチする行までにマッチするので、それを print すれば良い。

awk 'pattern1,pattern2'
awk '/REGEXP1/,/REGEXP2/'

読みやすさのために整形してあるせいで行指向なツールで扱いづらいデータに強い、気がする。でも、手元のテキストファイルを処理する場合は、テキストエディタで開いて該当部分だけカット&ペーストした方が早いような気もする。ワンライナーで何かする場合に不要なデータを除外するために使ったりするのが便利そう。

良い例がない(あるけど公開できない)のであれだけど。

  • redis-cli info の結果から、メモリ関連の部分だけを抽出する。
$ redis-cli info | awk '/# Memory/,/^\s+$/'
# Memory
used_memory:859152
used_memory_human:839.02K
used_memory_rss:5894144
used_memory_rss_human:5.62M
used_memory_peak:859152
used_memory_peak_human:839.02K
used_memory_peak_perc:100.00%
used_memory_overhead:845926
used_memory_startup:796232
used_memory_dataset:13226
used_memory_dataset_perc:21.02%
allocator_allocated:1403704
allocator_active:1691648
allocator_resident:8835072
total_system_memory:1029033984
total_system_memory_human:981.36M
used_memory_lua:41984
used_memory_lua_human:41.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.21
allocator_frag_bytes:287944
allocator_rss_ratio:5.22
allocator_rss_bytes:7143424
rss_overhead_ratio:0.67
rss_overhead_bytes:-2940928
mem_fragmentation_ratio:7.40
mem_fragmentation_bytes:5097888
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:49694
mem_aof_buffer:0
mem_allocator:jemalloc-5.2.1
active_defrag_running:0
lazyfree_pending_objects:0

awk(1): pattern scanning/processing - Linux man page

The pattern1, pattern2 form of an expression is called a range pattern. It matches all input records starting with a record that matches pattern1, and continuing until a record that matches pattern2, inclusive. It does not combine with any other sort of pattern expression.

awk Man Page - macOS - SS64.com

A pattern can consist of two patterns separated by a comma; in this case, the action is performed for all lines from an occurrence of the first pattern though an occurrence of the second.

とほほのAWK入門 - とほほのWWW入門

条件1, 条件2 を記述した場合、条件1が真になる行から、条件2が真になる行までマッチします。

$1=="START", $1=="END" { ... } # 第1フィールドがSTARTである行から、ENDである行までマッチ

特定の行から特定の行までを抽出する | ハックノート

例えば、BEGINが含まれる行からENDが含まれる行までを抽出したいときは、以下のようにします。

$ cat hogehoge.txt | awk '/BEGIN/,/END/'