Chubaka
Chubaka

Reputation: 3145

bash read strings and output as one key and multiple values

Assuming there is an input:

1,2,C

We are trying to output it as

KEY=1, VAL1=2, VAL2=C

So far trying to modify from here: Is there a way to create key-value pairs in Bash script?

for i in 1,2,C ; do KEY=${i%,*,*}; VAL1=${i#*,}; VAL2=${i#*,*,}; echo $KEY" XX "$VAL1 XX "$VAL2"; done

Output:

1 XX 2,c XX c

Not entirely sure what the pound ("#") and % here mean above, making the modification kinda hard.

Could any guru enlighten? Thanks.

Upvotes: 0

Views: 864

Answers (2)

xxfelixxx
xxfelixxx

Reputation: 6602

I would generally prefer easier to read code, as bash can get ugly pretty fast.

Try this:

key_values.sh

#!/bin/bash

IFS=,
count=0
# $* is the expansion of all the params passed in, i.e. $1, $2, $3, ...
for i in $*; do
    # '-eq' is checking for equality, i.e. is $count equal to zero.
    if [ $count -eq 0 ]; then
        echo -n "KEY=$i"
    else
        echo -n ", VAL${count}=$i"
    fi
    count=$(( $count + 1 ))
done

echo

Example

key_values.sh 1,2,ABC,123,DEF

Output

KEY=1, VAL1=2, VAL2=ABC, VAL3=123, VAL4=DEF

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246877

Expanding on anishsane's comment:

$ echo $1
1,2,3,4,5

$ IFS=, read -ra args <<<"$1"     # read into an array

$ out="KEY=${args[0]}"

$ for ((i=1; i < ${#args[@]}; i++)); do out+=", VAL$i=${args[i]}"; done

$ echo "$out"
KEY=1, VAL1=2, VAL2=3, VAL3=4, VAL4=5

Upvotes: 1

Related Questions