bash - 如何使用 sed 或 grep 和正则表达式 json 提取文本
问题描述
您好,我正在使用 curl 获取一些我需要清理的信息。这是来自 curl 命令:
{"ip":"000.000.000.000","country":"Italy","city":"Milan","longitude":9.1889,"latitude":45.4707, etc..
我需要将“Ita”作为输出,即该国的前三个字母。
阅读sed JSON 正则表达式后,我尝试适应导致
sed -e 's/^.*"country":"[a-zA-Z]{3}".*$/\1/
但这行不通。
你能帮忙吗?
解决方案
使用jq,您可以执行以下操作:
curl .... | jq -r '.country[0:3]'
如果您需要将国家设置为前 3 个字符,
jq '.country = .country[0:3]'
一些相当先进的bash:
{
read country
read city
} < <(
curl ... |
jq -r '.country[0:3], .city[0:3]'
)
然后:
$ echo "$country $city"
Ita Mil
推荐阅读
- apache-flink - Apache Flink 读取至少 2 条记录来触发 sink
- javascript - 将函数应用于多个字符串的最简洁方法?
- python - 如何检查我的 pandas csv 中是否有任何额外的列?
- facebook - FB Live 模式未显示已批准的 API
- node.js - 与 MongoDB 和 NodeJs 的并发写入冲突
- c++ - 我已经在 C++ 中创建了一个函数来递归地反转字符串,但是我怎样才能让这个函数在之后打印一个 endl?
- python - 在特定时间后停止从 API 中提取数据
- python - 如何通过svg文件在Tkinter python的平面图图像中查找对象?
- flutter - 颤振插件项目构建中断:找不到适用于 iOS 的 @import 模块
- javascript - 如何在单击或更改时获取 $(this) 选择器的值