首页 > 解决方案 > 有没有办法从日志中提取一个值并进一步使用它来使用 bash 提取另一个值

问题描述

我正在尝试从日志文件中读取一个值,然后根据该值搜索另一个文本。

下面是我的日志文件的样子。我只有 customerId ,订单 ID 是动态生成的

我想首先根据 customerId 捕获 orderId 并存储在变量中。

一旦成功,我想检查这个订单 ID 的状态,它是下面大约 10 行

最后,在控制台打印或写入文件都没关系

    2019-05-18 09:46:02.944 [thread-2         ] Orderprocesing:  Sending order info '{
  "customerName" : "jenny",
  "customerId" : "JE19802501",
  "customerphone" : null,
  "orderId" : "8456/72530548",
  "orderInfo" : {
    "Item" : "comic series 2018",
    "count" : "10"

  }
}'
.............................................................
.............................................................
2019-05-18 09:46:02.944 [thread-2         ] Orderprocesing:  Sending order info '{
  "customerName" : "jenny",
  "customerId" : "JE19802501",
  "customerphone" : null,
  "orderId" : "8456/82530548",
  "orderInfo" : {
    "Item" : "comic series 2019",
    "count" : "10"

  }
}'

.............................................................
.............................................................
2019-05-18 09:49:02.944 [thread-2         ] Orderprocesing:  status for 82530548 is success
.............................................................
.............................................................
.............................................................
2019-05-18 09:50:06.872 [thread-2         ] Orderprocesing:  status for 72530548 is success

我是新 bash,我设法将包含与 CustomerID 对应的 OrderId 的 10 行切片,但无法切片 OrderId 并将其存储在变量中

$ cat orderlog_may_18 grep -A 15 "JE19802501"

预期的结果是打印

customerId : JE19802501
orderId : 72530548
status for 72530548 is success
customerId : JE19802501
orderId : 82530548
status for 82530548 is success

标签: bashloggingawkgrep

解决方案


两行 bash,使用 sed。

ord=$(sed -n '/JE19802501/,/orderId/{/orderId/{s/[^0-9]//gp}}' orderlog_may18)
sed -n "/status for $ord/s/.*://p" orderlog_may18

$ord 存储 JE198002501 之后 orderId 行中的数字。然后打印状态行的尾端。

您应该能够在 bash 脚本中进行所需的格式设置。


推荐阅读