I have a string which is concatenation of "key":"value" pairs separated by "," like-


From this string, I have to grep for a specific string -- let's say KEY2 -- so the output of our command should be VALUE2.

  • 3
    Can the values contain quotes commas or colons? Is it JSON? – Jeff Schaller May 13 '19 at 12:54

Using pgrep:

grep -Po '(^|[ ,])KEY1:\K[^,]*'

or egrep and cut:

grep -Eo '(^|[ ,])KEY2:[^,]*' | cut -d: -f2-

For both methods, the Value is not allowed to contain comma.

If you had proper json, e.g.

{ "KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3" }

you could use jq:

jq ".KEY2"

With regular grep assuming VALUE doesn't contain a colon:

grep -o 'KEY2:[^,]\+' | grep -o '[^:]\+$'
  • @RoVo: added caveat – Thor May 13 '19 at 14:25

To grep only the value

echo $myString | grep -Po "(?<=KEY2:)[^,]*"


grep -Po "(?<=KEY2:)[^,]*" <<< $myString

Use awk, read key:value pair as record, read key, value as 1st and 2nd field.

awk -v RS=' *, *' -v FS=' *: *' '$1=="KEY2"{print $2}'  <<<$str
  • -v RS=' *, *' set record separator to , and it's surrounding space
  • -v FS=' *: *' set field separator to : and it's surrounding space
  • '$1=="KEY2"{print $2}' print value if key found. change "KEY2" to your desired key value.

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.