5

I have let's say arrays ar1 and ar2 I want both of these arrays be printed in two columns.

  printf "%s\t%s\n" "${ar1[@]}" "${ar2[@]}"

any ideas?

Raymond gsh
  • 338
  • 2
  • 13

1 Answers1

13

Assuming array elements don't contain newlines, paste can do this job:

ar1=(1 2 3 4 5 6)
ar2=(a b c d e f)
paste <(printf "%s\n" "${ar1[@]}") <(printf "%s\n" "${ar2[@]}")
1   a
2   b
3   c
4   d
5   e
6   f

Otherwise a pure BASH loop:

for ((i=0; i< "${#ar1[@]}"; i++)) do printf "%s\t%s\n" "${ar1[$i]}" "${ar2[$i]}"; done
1   a
2   b
3   c
4   d
5   e
6   f
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • 3
    +1 Was about to post the same. Note that array elements must not contain newlines...................................... – user000001 Oct 07 '15 at 17:04
  • Excuse me, what is exactly "%s\n" doing here? If you don't include it, it works anyways? Thank you! – msimmer92 Jan 22 '19 at 10:14
  • Thank you. By the way, I tried this in linux and mac and it doesn't work, and shows me the following message: "pastevariables.sh: 2: pastevariables.sh: Syntax error: "(" unexpected". Any thoughts of what might be happening? Thank you (I copied and paste exactly your example, but I put it inside an sh file. First line #!/bin/bash, second and third lines your arrays, third line the paste command) – msimmer92 Jan 22 '19 at 13:12
  • 1
    Nevermind. I saw that when I run it with sh doesn't work but if I run it "bash script.sh" it works, so it must be the shell. – msimmer92 Jan 22 '19 at 13:16
  • What happens if the elements/strings in the first column have different lengths between them, would the two table columns still be equidistant? – Luis Chaves Rodriguez Mar 04 '21 at 18:28
  • You can pipe to `column -t` to get tabular output. – anubhava Mar 04 '21 at 18:35