输出循环数组数据以分隔 bash 中的列

Output looped array data to separate columns in bash

我有三个循环处理数组数据并打印到同一个日志文件。我想将每个循环的输出排序为使用 bash 代码由制表符分隔的列:

1   2   3
1   2   3
1   2   3
1   2   3
1   2   3

注意:1代表循环1的内容,2代表循环2的内容,3代表循环3的内容

declare -a Array1
declare -a Array2
declare -a Array3

for (( i = 0 ; i < 9 ; i++))
do
echo "${Array1[$i]}"
done | tee -a log.txt


for (( i = 0 ; i < 9 ; i++))
do
echo "(( ${Array1[$i]}-${Array2[$i]} ))" | bc
done | tee -a log.txt


for (( i = 0 ; i < 9 ; i++))
do
echo "${Array3[$i]}"
done | tee -a log.txt

我用 column 命令尝试了一些东西,但它没有像上面概述的那样工作。

最简单的选择可能是使用单个循环。

另一种方法是采用您已有的输出格式并将其转换为列。这是一种方法:

# Read the concatenated results into an array, $results
IFS=$'\n' read -d '' -r -a results < log.txt

# Print the concatenated results in columns
for (( i=0 ; i<9; i++ )) ; do
    printf '%s\t%s\t%s\n' "${results[i]}" "${results[i+9]}" "${results[i+18]}"
done

如果您不需要 log.txt 文件,您可以在计算结果时将结果放入数组中(使用任意多的循环),然后打印出来。