How to print two arrays side by side using a bash script?

I could not find a good and simple answer to this question neither on google nor here on stackoverflow.

Basically, I have two arrays that I need to print side by side in the terminal, since one array is a list of terms, and the other is a definition of terms. Does anyone know a good way to do this?

Thanks in advance.

+6
source share
2 answers

You can use the C loop to accomplish this, assuming both arrays are the same length:

for ((i=0; i<=${#arr1[@]}; i++)); do printf '%s %s\n' "${arr1[i]}" "${arr2[i]}" done 
+6
source

Here's the "one line":

 paste <(printf "%s\n" "${terms[@]}") <(printf "%s\n" "${defs[@]}") 

This will create rows consisting of the term and def, separated by a tab, which, strictly speaking, can be “side by side” (since they are not in the columns). If you knew how wide the first column is, you can use something like:

 paste -d' ' <(printf "%-12.12s\n" "${terms[@]}") <(printf "%s\n" "${defs[@]}") 

which will place or trim the terms to 12 characters exactly, and then put a space between the two columns instead of the ( -d' ' ) tab.

+8
source

Source: https://habr.com/ru/post/944824/


All Articles