Monday, April 4, 2022

[SOLVED] How can I find an empty name using grep in bash json?

Issue

How can I find an empty name using grep?

my json files

{
    "IDS": [
        {
            "digest": "sha256:b97"
        },
        {
            "digest": "sha256:d25"
        },
        {
            "digest": "sha256:c40",
            "tag": "0"
        }
    ]
}

I'd like to use grep to find a digest file without tag.

i want to like this result.

sha256:b97
sha256:d25

I have used 'has(tag) == false' in jq, but my environmental nature is not available using jq

I wonder how to use it without jq, python and other tools.

Thank you for reading my post. XD


Solution

If jq is out of the question, an awk alternative might be:

awk '/"digest"[^,]+$/{gsub(/"/,""); print $NF}' input.json

If input is minified:

$ echo $foo
{ "IDS": [ { "digest": "sha256:b97" }, { "digest": "sha256:d25" }, { "digest": "sha256:c40", "tag": "0" } ] }
$
$ awk -vRS='[{}]' 'NF==2 && $0 ~ /"digest"/{gsub(/"/,"");print $NF}' <<< "$foo"
sha256:b97
sha256:d25


Answered By - Thomas Hansen
Answer Checked By - Candace Johnson (WPSolving Volunteer)