如何使用Unix脚本从JSON格式文件提取Countryid与History值
需求:从重复JSON结构文件提取指定字段
我有一个包含重复JSON结构的文件,需要从中提取Countryid和History字段的值,输出格式要求如下:
Countryid: 0115 History: 20220621
文件内容示例:
{ "Music": "1410", "Countryid": "0115", "History": "20220621", "Legend": "/api/legacysbo/bondue", "Sorting": "/api/dmplus/test", "Nick": "hinduja", "Scenario": [ "K", "A", "S", "F", "D" ] }, { "Music": "1466", "Countryid": "1312", "History": "20221012", "Legend": "/api/legacysbo/grenob", "Sorting": "/api/dmplus/prod", "Nick": "Grenoble", "Scenario": [ "K", "A", "S", "F", "D" ] },
实现方案(Unix脚本)
方法1:使用jq(推荐,JSON专用工具)
jq是处理JSON的标准Unix工具,能精准解析JSON结构,不受换行、空格变化影响。
执行命令:
jq -r '.[] | "Countryid: \(.Countryid) History: \(.History)"' your_file.json
- 说明:
-r:输出原始字符串(不带引号).[]:遍历数组中的每个JSON对象- 字符串拼接部分:提取
Countryid和History字段值,按要求格式输出
如果文件是多个独立JSON对象(未被数组包裹),添加--slurp参数转为数组处理:
jq -r --slurp '.[] | "Countryid: \(.Countryid) History: \(.History)"' your_file.json
方法2:使用awk(适合格式固定的场景)
若系统未安装jq,可使用awk匹配字段行拼接输出。注意此方法依赖JSON格式稳定(如Countryid始终在History之前,每行格式一致)。
执行命令:
awk -F'"' '/"Countryid"/{cid=$4} /"History"/{print "Countryid: " cid " History: " $4}' your_file.json
- 说明:
-F'"':将双引号设为字段分隔符- 匹配
Countryid行时,提取第4个字段(即字段值)存入变量cid - 匹配
History行时,拼接cid和当前行的字段值输出
内容的提问来源于stack exchange,提问作者O_Athens
相关产品推荐
相关产品推荐

