Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


使用 awk 提取 JSON 字符串中的字段

Linux awk JSON 大约 904 字

需求

aaa.log文件中(文本为JSON串)中提取出phone字段对应的值。

{"phone":"18633333333","code":"333333"}
{"phone":"18633333333","code":"000000"}
{"aaa":"888888","code":"888888","phone":"123456"}
{"phone":"18611111111","code":"111111"}
{"phone":"18655555555","code":"555555"}
{"aaa":"888888","phone":"7890123","code":"888888"}

substr 字符串解决

适用于字段长度相同的情况

awk -F '"phone":"' '{print substr($2,0,11)}' aaa.log

match 正则匹配

正则:\"([^\"]*)\",匹配后取数组a0个元素。

awk -F '"phone":' 'match($2,/\"([^\"]*)\"/,a){print a[0]}' aaa.log

输出,带双引号:

"18633333333"
"18633333333"
"123456"
"18611111111"
"18655555555"
"7890123"

match 正则匹配方法二

正则:\"([^\"]*)\",匹配后取数组a1个元素。

awk -F '"phone":' 'match($2,/\"([^\"]*)\"/,a){print a[1]}' aaa.log

输出,不带双引号:

18633333333
18633333333
123456
18611111111
18655555555
7890123

补充

执行match匹配时可能有警告信息如下,原因是awk版本5.0.0之后会有此提示信息,4.2.1版本无此警告信息。

awk: cmd. line:1: warning: regexp escape sequence `\"' is not a known regexp operator
阅读 8265 · 发布于 2019-10-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批