0

How do I convert an array into a string with a dash '-' in between in bash. For eg, I have this array

arr=(a b c d e)

I want to convert it into a string "a-b-c-d". I figured out this "a-b-c-d-e," but there is an unwanted dash at the end. Is there an efficient way of doing this?

Thanks

apix
  • 11
  • 2
  • See: [How can I join elements of an array in Bash?](https://stackoverflow.com/q/1527049/3776858) – Cyrus Oct 20 '22 at 23:15

2 Answers2

3

This is where the "${arr[*]}" expansion form is useful (note the double quotes and the * index). This joins the array elements using the first character of the IFS variable

arr=(a b c d e)

joined=$(IFS='-'; echo "${arr[*]}")
declare -p joined
# => declare -- joined="a-b-c-d-e"

But if you want all-but-the-last elements, you'll combine this with the ${var:offset:length} expansion

joined=$(IFS='-'; echo "${arr[*]:0: ${#arr[@]} - 1}")
declare -p joined
# => declare -- joined="a-b-c-d"

This one's a little tricker. The offset and length parts of that expansion are arithmetic expressions. I'm calculating the length as "the number of elements in the array minus one".

Note how I'm defining IFS inside the command substitution parentheses: this is overriding the variable in the subshell of the command substitution, so it won't affect the IFS variable in your current shell.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

Using awk if you want to remove the last entry

$ awk -vOFS=- '{NF--;$1=$1}1' <<<${arr[@]}
a-b-c-d

or the complete array

$ awk -vOFS=- '{$1=$1}1' <<<${arr[@]}
a-b-c-d-e
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134