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=)
#!/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,"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With