用正则表达式解析sed

时间:2018-01-25 16:11:02

标签: regex bash sed

我有一个文件:

"data_personnel": [
    {
        "id": "1",
        "name": "Mathieu"
    }
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

我执行此命令以获取struct_hospital

中的所有geo值
sed -n "/\"struct_hospital\"/,/^\],$/s/^[[:blank:]]*\"geo\":[[:blank:]]\+\"\([^\"]*\)\",/\1/p my_file

我的sed命令应该更改什么才能获得nb的所有值? geo是:“geo”:“value”,(用逗号) nb是:“nb”:“value”(不带逗号)

我不明白..

3 个答案:

答案 0 :(得分:3)

使用 jq 工具的正确方法:

  

获取 nb

的所有值
echo "{ $(cat yourfile) }" | jq -r '.struct_hospital[].nb'

输出:

 
SMITH
12
20
1
5

答案 1 :(得分:0)

如果我理解正确,这适用于您的输入

sed -n "/\"struct_hospital\"/,/^\],$/s/^[[:blank:]]*\"nb\":[[:blank:]]\+\"\([^\"]*\)\"$/\1/p" my_file

不同之处在于,有一个行尾字符($)而不是逗号。 (而且我添加了一个缺少的双引号)

答案 2 :(得分:0)

With the exact text you provided, the following sed command would be enough to output all the "nb" values :

sed -n 's/.*"nb": "\([^"]*\)".*/\1/p'

ideone test (note that ideone trims the leading empty line corresponding to the first empty "nb" value, but you should get it when executing the command).

相关问题