有没有一种方法可以从日志中提取值并进一步使用bash来提取另一个值

时间:2019-07-19 16:10:09

标签: bash logging awk grep

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

下面是我的日志文件的外观。我所拥有的只是customerId,订单ID是动态生成的

我想首先基于customerId捕获orderId并将其存储在变量中。

成功后,我要检查此订单ID的状态,该订单ID在下面大约10行

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

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

  }
}'

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

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

$ cat orderlog_may_18 grep -A 15 "JE19802501"

预期结果将打印

customerId : JE19802501
orderId : 72530548
status for 72530548 is success

2 个答案:

答案 0 :(得分:0)

使用sed进行两行bash操作。

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脚本中进行所需的格式化。

答案 1 :(得分:0)

$ awk -v trgt='JE19802501' '
    { gsub(/[",]/," "); $1=$1 }
    $1 == "customerId"                  { cust=$NF; print }
    ($1 == "orderId") && (cust == trgt) { ordr=$NF; print }
    $0 ~ ("status for " ordr " is")     { sub(/.*: /,""); print }
' file
customerId : JE19802501
orderId : 72530548
status for 72530548 is success
相关问题