Crazy
Crazy

Reputation: 139

sed parsing with regex

I have a file:

"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"
    }
]

I do this command for get all value of geo in struct_hospital

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

What should I change on my sed command for get all value of nb ? geo is: "geo":"value", (with comma) nb is: "nb":"value" (without comma)

I don't understand ..

Upvotes: 0

Views: 94

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The right way with jq tool:

get all value of nb

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

The output:

 
SMITH
12
20
1
5

Upvotes: 3

Aaron
Aaron

Reputation: 24802

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).

Upvotes: 0

Chris Lear
Chris Lear

Reputation: 6732

If I've understood you correctly, this works for your input

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

The difference is that there's an end-of-line character ($) rather than a comma. (And I've added a missing double quote)

Upvotes: 0

Related Questions