7

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.

Ishpreet
  • 5,230
  • 2
  • 19
  • 35

2 Answers2

12
[akshay@localhost tmp]$ arr=("element1" "element2" "element3")
[akshay@localhost tmp]$ joined=$(printf ",'%s'" "${arr[@]}")
[akshay@localhost tmp]$ echo ${joined:1}
'element1','element2','element3'
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
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.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18