Store comma key = value pair in string before $ key, variable $ value in wrapper

In my bash shell script, I have a comma, a pair of values ​​as one line. How to parse and store each key and value in separate variables.
For example,
string1="key1=value1,key2=value2"



I want to convert this,
echo 'key1 = value1' >> key1.txt echo 'key2 = value2' >> key2.txt

<br / "> The number of key pairs, values ​​in line1 will be dynamic. How do I do this in a shell script?
I used cut to get the key and value. But I'm not sure how a loop consisting of a number pairs per line.

string1='key1=value1'
KEY=$(echo $string1 | cut -f1 -d=)
VALUE=$(echo $string1 | cut -f2 -d=)

      

+3


source to share


2 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 it read

also enters the loop body while

with the last- ,

segmented token.

gives:

key1 = value1
key2 = value2

      




To write key-value pairs for 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,"

      

+5


source


Assuming you are talking about bash, something like this might work:



#!/bin/bash

string1="key1=value1,key2=value2"
OIFS="$IFS"
IFS=","

for pair in ${string1}
do
        declare $pair
done

IFS="$OIFS"

echo $key1
echo $key2

      

-2


source







All Articles