sed to match zero or more number of spaces in a string
8,871
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/'
Related videos on Youtube
Author by
Admin
Updated on September 18, 2022Comments
-
Admin over 1 year
function getVal { sedPattern='s/^.*"keyVal":"\([^"]*\)".*$/\1/' finalSedPattern=${sedPattern/keyVal/$2} echo $(sed $finalSedPattern <<< $1) }
This is my Json parser written using
sed
. It takes json string, key name and returns the value like,myJson='{"hello":"sk"}' 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?