9

How to convert array elements with single quotes and comma in Bash.

arr=("element1" "element2" "element3")
#element1 element2 element3

Desired result 'element1','element2','element3'

From Martin Clayton answer comma seprated values are achieved using IFS,

SAVE_IFS="$IFS"
IFS=","
ARRJOIN="${arr[*]}"
IFS="$SAVE_IFS"

echo "$ARRJOIN"
#element1,element2,element3

But how to add single quotes to each element.

2 Answers 2

15
[akshay@localhost tmp]$ arr=("element1" "element2" "element3")
[akshay@localhost tmp]$ joined=$(printf ",'%s'" "${arr[@]}")
[akshay@localhost tmp]$ echo ${joined:1}
'element1','element2','element3'
Sign up to request clarification or add additional context in comments.

2 Comments

Why ${joined:1} and not simply ${joined}? Or: what does the :1 do?
Ah, it removes the first character. And the join of course produces a extra comma at the end.
1

Just use sed:

sed -E "s/([[:alnum:]]+)/'&'/g;s/ /,/g" <<< ${arr[@]}

One the first sed command, surround all alpha numeric strings with single quotes and on the second command, replace the spaces with commas.

1 Comment

This won't work right if any elements contain non-alphanumeric characters (spaces, punctuation, etc).

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.