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.

7
  • 1
    Here is the syntax explanation: mywiki.wooledge.org/BashFAQ/073 Commented Jul 18, 2016 at 7:06
  • 2
    btw, for this case, your code can be shortened to: IFS=, read KEY VAL1 VAL2 <<< "1,2,C" Commented Jul 18, 2016 at 7:09
  • hi anishsane, your answer is BRILLIANT! Commented Jul 18, 2016 at 7:10
  • 1
    Surely that page explains it. Do check BashFAQ73 & BashFAQ100 (which is liked in the first page - FAQ#73) They should be sufficient to explain what % & # do in above syntax. Commented Jul 18, 2016 at 7:32
  • 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) Commented Jul 18, 2016 at 8:15

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Looks good! but not quite sure what "$*" and "-eq" means. Could you enlighten?
Added some comments.
Thank you so much!
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

1 Comment

Thank you so much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.