bash printf two arrays in two columns

2020-07-13 11:50发布

问题:

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?

回答1:

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