Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store comma separated key=value pair in a string to $key, $value variable in shell

In my bash shell script I have a comma separated key,value pairs in a form of single string. How to parse and store each key and value in separate variables.
For example,
string1="key1=value1,key2=value2"

I want to convert this to,
echo 'key1 = value1' >> key1.txt echo 'key2 = value2' >> key2.txt
The number of key,value pairs in string1 will be dynamic. How to do this in shell script?
I have used cut to get the key and value. But I am not sure how loop that over numbers of pairs ina string.

string1='key1=value1'
KEY=$(echo $string1 | cut -f1 -d=)
VALUE=$(echo $string1 | cut -f2 -d=)
like image 475
Naresh Avatar asked Jun 19 '17 20:06

Naresh


1 Answers

#!/bin/bash

string1="key1=value1,key2=value2"

while read -d, -r pair; do
  IFS='=' read -r key val <<<"$pair"
  echo "$key = $val"
done <<<"$string1,"

Note the trailing , in "$string1,", which ensures that read also enters the while loop body with the last ,-separated token.

yields:

key1 = value1
key2 = value2

To write the key-value pairs to sequentially numbered files (key<n>.txt, starting with 1):

#!/bin/bash

string1="key1=value1,key2=value2"

i=0
while read -d, -r pair; do
  IFS='=' read -r key val <<<"$pair"
  echo "$key = $val" > "key$((++i)).txt"
done <<<"$string1,"
like image 80
mklement0 Avatar answered Nov 15 '22 05:11

mklement0