TransWikia.com

Grep value of a specific key from a String, concatenated of key : value pairs

Unix & Linux Asked by Abhijeet srivastava on October 31, 2021

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.

4 Answers

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.

Answered by dedowsdi on October 31, 2021

To grep only the value

printf '%sn' "$myString" | grep -Po "(?<=KEY2:)[^,]*"

or

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

Answered by bu5hman on October 31, 2021

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

grep -o 'KEY2:[^,]+' | grep -o '[^:]+$'

Answered by Thor on October 31, 2021

Using PCRE-enabled grep implementations:

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
"VALUE2"
$ jq -r .KEY2
VALUE2

Answered by pLumo on October 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP