bash 读取字符串并输出为一键多值

bash read strings and output as one key and multiple values

假设有一个输入:

1,2,C

我们正在尝试将其输出为

KEY=1, VAL1=2, VAL2=C

到目前为止尝试从这里进行修改: 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

输出:

1 XX 2,c XX c

不完全确定上面的磅 ("#") 和 % 是什么意思,使修改有点困难。

有哪位大神能开导一下吗?谢谢。

我通常更喜欢更容易阅读的代码,因为 bash 很快就会变得丑陋。

试试这个:

key_values.sh

#!/bin/bash

IFS=,
count=0
# $* is the expansion of all the params passed in, i.e. , , , ...
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

例子

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

输出

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

扩展 anishsane 的评论:

$ echo 
1,2,3,4,5

$ IFS=, read -ra args <<<""     # 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