How do I change a bash array into a string with this pattern? Let's say I have arr=(a b c d)
and I want to change to this pattern
'a' 'b' 'c' 'd'
with the white space in between.
PS-I figured out this pattern 'a' 'b' 'c' 'd'
but not sure how to put " "
instead of just " "
in between.
CodePudding user response:
Like this:
#!/bin/bash
arr=(a b c d)
str="${arr[@]}"
str=${str// / } # Parameter Expansion
sed "s/[a-z]/'&'/g" <<< "$str"
Output
'a' 'b' 'c' 'd'
Check
See: http://mywiki.wooledge.org/BashFAQ/073 and "Parameter Expansion" in man bash. Also see http://wiki.bash-hackers.org/syntax/pe.
CodePudding user response:
I would do it like so:
$ str=$(printf "'%s' " "${arr[@]}")
$ str=${str% }
$
$ echo "$str"
'a' 'b' 'c' 'd'