書式設定されたテキストから値を抽出する

書式設定されたテキストから値を抽出する

テキストファイルから変数を抽出する簡単な方法はありますか?

たとえば、次のような出力がありますab

This is ApacheBench, Version 2.3 <$Revision: 1638069 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking bar (be patient)
Finished 1206 requests


Server Software:        Jetty(9.0.z-SNAPSHOT)
Server Hostname:        bar
Server Port:            5500

Document Path:          /foo/1
Document Length:        148 bytes

Concurrency Level:      15
Time taken for tests:   30.041 seconds
Complete requests:      1206
Failed requests:        0
Total transferred:      359686 bytes
HTML transferred:       178636 bytes
Requests per second:    40.15 [#/sec] (mean)
Time per request:       373.643 [ms] (mean)
Time per request:       24.910 [ms] (mean, across all concurrent requests)
Transfer rate:          11.69 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       47  108  36.0     98     328
Processing:    73  264 782.5    150    7951
Waiting:       73  255 721.5    148    7886
Total:        129  371 783.5    259    8039

Percentage of the requests served within a certain time (ms)
  50%    259
  66%    293
  75%    324
  80%    340
  90%    413
  95%    525
  98%    683
  99%   6421
 100%   8039 (longest request)

name: value値(一致、以下の例を参照)を抽出し、1つのステップで変数に割り当てたいと思います。 (ab一部のデータはcsvにエクスポートできますが、残りはフォーマットされたテキストでのみ使用できることを知っています。)

これまでに私が見つけた最高は次のとおりです。

path=$(cat text|grep 'Document Path:'|awk -F: '{ split($2, z, " "); print z[1]}')
total=$(cat text|grep 'Total transferred:'|awk -F: '{ split($2, z, " "); print z[1]}')
#[...]

しかし、これは少し繰り返されると思います。アッWard - 作業のためのより簡単な方法またはより良いツールはありますか?

ベストアンサー1

私は通常、次のパターンを使用します。

. <(
    awk 'BEGIN{print "shellvarname=\"value\""}'
)

awkこれは、シェル変数割り当て構文に使用できるステートメントを生成するために使用されます。この結果は(.)からのものです。

特定の要件に応じて、次のオプションがあります。

. <(
    awk -F': *' '
      /Document Path/{printf "%s=\"%s\"\n", "path", $2}
      /Total transferred/{printf "%s=\"%s\"\n", "total", $2}
    ' file
)

またはより短い

. <(
    awk '
      /Document Path/{printf "%s=\"%s\"\n", "path", $3}
      /Total transferred/{printf "%s=\"%s\"\n", "total", $3}
    ' file
)

おすすめ記事