2

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

KEY1:VALUE1, KEY2:VALUE2, KEY3:VALUE3

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

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

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"
| improve this answer | | | | |
0

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

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

To grep only the value

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

or

grep -Po "(?<=KEY2:)[^,]*" <<< $myString
| improve this answer | | | | |
0

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.
| improve this answer | | | | |

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.