在平时工作中,我们有时候需要对JSON 的某一个字段进行提取,
样例数据 :
{"a1":22,"a2":"23"}
{"a2":"23","a1":2233,a3:"22"}
可以使用 grep 完成功能:
grep -Po 'test[" :]+\K[^"]+' example.txt
其中:
P, --perl-regexp
Interpret PATTERN as a Perl regular expression. This is highly experimental and grep -P may warn of nimplemented features.
test : 为待提取的字段名
example.txt : 需要处理的json文件
Tips:
1.此种方法只能适用于 简单类型的提取,并且数据是字符串类型,也就是 " " (双引号)括起来 的数据 , a1字段 不满足要求。
提取 a2 , 可行
[cloudera-scm@app7 test]$ cat test.txt | grep -Po 'a2[" :]+\K[^"]+'
23
23
提取a1, 不可行
[cloudera-scm@app7 test]$ cat test.txt | grep -Po 'a1[" :]+\K[^"]+'
22,
2233,a3:
---------------- 未完待续 -------------