9

I couldn't 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 into the terminal side by side since one array is a list of terms and the other the terms's definitions. Does anyone know a good way of doing this?

Thanks in advance.

1
  • Use an associative array? Commented May 12, 2013 at 18:29

2 Answers 2

13

Here's a "one-liner":

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

This will create lines consisting of a term and a def separated by a tab, which might not, strictly speaking, be "side by side" (since they're not really in columns). If you knew how wide the first column should be, you could use something like:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

For those who use shell in POSIX mode: unix.stackexchange.com/questions/151911/…
9

You can use a C-style for 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

2 Comments

Wouldn't it be easier to loop through array indices? Like i in "${!arr1[@]}"?
@oguzismail yes, and it would better handle sparse arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.