function getVal {
  echo $(sed $finalSedPattern  <<< $1)

This is my Json parser written using sed. It takes json string, key name and returns the value like,

val=$(getVal $myJson hello)
echo $val

prints, sk

But sometimes, my json string may or may not contain space as,

myJson='{"hello" : "sk"}'

In that case, the function fails. I tried with tweaking the above pattern by adding [ ] to match zero or more spaces as,

sedPattern='s/^.*"keyVal"[ ]+:"\([^"]*\)".*$/\1/'

It throws error as,

unterminated `s' command

How can i give non-capturing pattern groups inside sed?


Your sedPattern has some issue with quotes. you are trying to match the same quote twice. Also, + is used for one or more. for 0 or more, use *.
caution: code below is untested, but should get you going.

sedPattern='s/^.*"keyVal"[ ]*:.*\(".*"\).*$/\1/'


You should quote variable expansions (just one example from your code):

sed $finalSedPattern

is unquoted and will be split on spaces (when used). You should use:

sed "$finalSedPattern"

Your function with quotes:

function getVal {  
    echo "$(sed "$finalSedPattern"  <<< "$1")"

And with optional spaces:

function getVal {
    sedPattern='s/^.*"keyVal"[ ]\{0,\}:[ ]\{0,\}"\([^"]*\)".*$/\1/1'
    echo "$(sed "$finalSedPattern"  <<< "$1")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.