首页 > 解决方案 > 如何使用 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/

但这行不通。

你能帮忙吗?

标签: bashcurlsedexpression

解决方案


使用,您可以执行以下操作:

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

推荐阅读