1

I have an array in bash...say, my_array:

my_array={1,2,3,4}

I need two requirements for this: 1) Print all of these elements on the same line, and 2) Separate each element with a tab.

When I print the elements out, here is what the output should be:

1    2    3    4

With each "gap" in between the elements being a tab.

Any suggestions on how to do this would be appreciated. Thank you.

EDIT Here's what I've tried so far:

1) I know I can print out an array on the same line as so:

echo {my_array[*]}

2) To get the desired tabs, I've tried making a variable with just a tab inside, and adding it to my array between each element:

temp="    "

for(...)
do
    ((my_array+=$i))
    ((my_array+=$temp))
done

This, however, gives me an error.

EDIT 2 Solution provided by Inan

This works:

printf '%s\t' "${my_array[@]}"

However, a couple things here; how would I delete the last tab, after the very last element?

user545642
  • 91
  • 1
  • 14
  • 1
    What have you tried so far? – Stuart Jan 29 '19 at 10:41
  • I'll put it in the EDIT - sorry, I completely forgot about this part. – user545642 Jan 29 '19 at 10:43
  • @DarrelGulseth: did you mean to add `\t` between the elements in the array or when printing it? – Inian Jan 29 '19 at 10:50
  • @Inian, the solution you provided did work. However, I still have two more concerns: how would I get rid of the last tab (I don't want the tab after the last element). I also want a new line after the array has finished printing. – user545642 Jan 29 '19 at 10:51
  • @DarrelGulseth: Use the most voted answer in the linked duplicate. Do `join_by() { local IFS="$1"; shift; echo "$*"; }` and define an array as `arr=(1 2 3 4)` and call the function as `join_by $'\t' "${arr[@]}"` – Inian Jan 29 '19 at 12:00
  • That's not a `bash` array; it's a regular string with the literal value `{1,2,3,4}`. `my_array=(1 2 3 4)` (or `my_array=({1,2,3,4})` if you really want to use the unnecessary brace expansion here) creates an array. – chepner Jan 29 '19 at 14:51
  • Thanks guys! I retried Mihai's answer and it worked! – user545642 Jan 29 '19 at 18:59

1 Answers1

0

Why not using "tr"?

my_array={1,2,3,4}
echo $my_array | tr "," "\t"

Result:

{1      2       3       4}

If:

my_array=(1,2,3,4)
echo $my_array | tr "," "\t"

Result:

1       2       3       4
Mihai M
  • 21
  • 2