bash 如何使用bash脚本并排打印两个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16510592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:24:35  来源:igfitidea点击:

How to print two arrays side by side with bash script?

arraysbashprintingawkecho

提问by Aslet

I couldn't find a good and simple answer to this question neither on google nor here on stackoverflow.

无论是在 google 上还是在 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.

提前致谢。

回答by rici

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:

这将创建由一个由制表符分隔的 term 和 def 组成的行,严格来说,这可能不是“并排”(因为它们实际上不在列中)。如果您知道第一列应该有多宽,您可以使用以下内容:

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' ').

这会将术语填充或截断为 12 个字符,然后在两列之间放置一个空格而不是制表符 ( -d' ')。

回答by jordanm

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

您可以使用 C 样式的 for 循环来完成此操作,假设两个数组的长度相同:

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