0

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.

Community
  • 1
  • 1
Chubaka
  • 2,933
  • 7
  • 43
  • 58
  • 1
    Here is the syntax explanation: http://mywiki.wooledge.org/BashFAQ/073 – anishsane Jul 18 '16 at 07:06
  • 2
    btw, for this case, your code can be shortened to: `IFS=, read KEY VAL1 VAL2 <<< "1,2,C"` – anishsane Jul 18 '16 at 07:09
  • hi anishsane, your answer is BRILLIANT! – Chubaka Jul 18 '16 at 07:10
  • Byw, I don't see the page explains % and #? – Chubaka Jul 18 '16 at 07:11
  • 1
    Surely that page explains it. Do check [BashFAQ73](http://mywiki.wooledge.org/BashFAQ/073) & [BashFAQ100](http://mywiki.wooledge.org/BashFAQ/100#Substituting_part_of_a_string) (which is liked in the first page - FAQ#73) They should be sufficient to explain what `%` & `#` do in above syntax. – anishsane Jul 18 '16 at 07:32
  • IFS=, read KEY VAL1 VAL2 <<< "1,2,c"; echo $KEY" XX "$VAL1 XX "$VAL2" works fine in the bash command line. However, if I put this command into a .sh file and execute, an error message "Syntax error: redirection unexpected" will pop out. May I know the reason? tHANKS – Chubaka Jul 18 '16 at 07:38
  • 1
    @Chubaka: Try adding the line `#!/bin/bash` in the beginning of your script. The error is likely due to the redirection operator `<<<` not available in your native shell (`/bin/sh` maybe) – Inian Jul 18 '16 at 08:15

2 Answers2

1

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
xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
1

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352