【问题标题】:Output looped array data to separate columns in bash输出循环数组数据以分隔 bash 中的列
【发布时间】:2016-12-13 09:38:20
【问题描述】:

我有三个循环处理数组数据并打印到同一个日志文件。我想使用 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 命令尝试了一些东西,但没有像上面描述的那样工作。

【问题讨论】:

  • 为每个循环使用不同的文件,然后使用粘贴将它们连接起来:patse log[1-9].txt
  • @Joe Lo:您打算使用单个循环打印所有列吗?还是只为每一列单独循环?
  • @Indian:单循环也是可以的。
  • @user000001:不过我更喜欢更清洁的解决方案 :))明天试试。

标签: arrays bash loops multiple-columns


【解决方案1】:

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

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

# 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 文件,您可以在计算时将结果放入一个数组中(使用任意数量的循环),然后打印出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2021-06-28
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2018-10-20
    相关资源
    最近更新 更多