问题
I have a string containing a list of key-value pairs like this: "a:1,b:2,c:3". I would like to extract a value for a specified key so that e.g. I would get "1" for "a". I was planning to do it with a regex like this:
'(?<=(^|,)$KEY:)^,*'
but it seems grep doesn't support lookarounds. (I'm not even sure this regex works correctly.) Is there another way?
回答1:
You may use
grep -oP "(?:^|,)$KEY:\K[^,]+"
The -o
option outputs matches. -P
enables PCRE engine. The double quotes are necessary for string interpolation so that $KEY
could be interpolated.
The pattern matches:
(?:^|,)
- start of string or comma$KEY
- theKEY
variable:
- colon\K
- match reset operator that discards the whole text matched so far[^,]+
- 1+ chars other than,
回答2:
Keep it simple. You don't need all this look-a-whatever stuff, just do a simple string comparison of the field you want and then print the other field you want with awk:
$ awk -v key="a" -v RS=',' -F':' '$1==key{print $2}' <<< "a:1,b:2,c:3,"
1
That awk script will work with any awk in any shell on any UNIX box. How you pass the string to awk will be shell-dependent the <<<
is a bash-ism but you can use this instead:
$ echo "a:1,b:2,c:3," | awk -v key="a" -v RS=',' -F':' '$1==key{print $2}'
1
or do other things depending if the string you want parsed is stored in a variable or a file or....
回答3:
You can use read
with an IFS
with colon and comma as field separators like this:
IFS=':,' read -ra arr <<< "a:1,b:2,c:3"
This will give you this array:
declare -p arr
declare -a arr=([0]="a" [1]="1" [2]="b" [3]="2" [4]="c" [5]="3")
if you want to list key-value pairs then use:
for ((i=0; i<${#arr[@]}; i+=2)); do echo "${arr[i]} => ${arr[i+1]}"; done
a => 1
b => 2
c => 3
To be able to fetch a single value for a given key, you may use this sed
:
k=a; sed -E "s/(^|.*,)$k:([^,]*).*/\2/" <<< "a:1,b:2,c:3"
1
k=b; sed -E "s/(^|.*,)$k:([^,]*).*/\2/" <<< "a:1,b:2,c:3"
2
k=c; sed -E "s/(^|.*,)$k:([^,]*).*/\2/" <<< "a:1,b:2,c:3"
3
来源:https://stackoverflow.com/questions/51087059/extract-value-from-a-list-of-key-value-pairs-using-grep