簡體   English   中英

如何使用Bash打印特定的數組行?

[英]How to print specific rows of arrays using Bash?

我目前正在使用bash中的矩陣。 我在文件中有一個2x4矩陣:

1    2    3    4
5    6    7    8

我已從該文件中讀取數據,並將所有這些元素存儲在一個數組中,例如:

my_arr={1 2 3 4 5 6 7 8}

接下來,通過管道傳輸回顯輸出,以便將空格更改為制表符:

echo ${my_arr[@]} | tr ' ' '\t'
**output**: 
my_arr={1    2    3    4    5    6    7    8}

現在我的問題是,我希望每打印四個元素后就有一個NEW-LINE; 換句話說,我是否可以逐行或逐行打印數組?

編輯這是我實際代碼中的內容:

array=()
cols #This contains number of columns

while read line1 <&3
do
    for i in $line1
    do
        array+=($i)
    done
done 3<$2

#Now, array has all the desired values. I need to print them out.

這是所需的輸出:

1    2    3    4
5    6    7    8

這是我數組中的內容:

(1 2 3 4 5 6 7 8)

嘗試這個:

printf '%s\t%s\t%s\t%s\n' "${my_arr[@]}"

格式字符串有四個用\\t (制表符)分隔並以\\n (換行符)結尾的字段說明符(所有%s只是純字符串),它將以該格式一次打印四個數組元素。

一種可能的(丑陋的)解決方案是將矩陣的大小存儲在單獨的變量rowscols 請嘗試以下操作:

set -f                      # prevent pathname expansion
array=()
rows=0
while read line1 <&3; do
    vec=($line1)            # split into elements
    cols=${#vec[@]}         # count of elements
    array+=(${vec[@]})
    rows=$((++rows))        # increment #rows
done 3<"$2"

# echo $rows $cols          # will be: 2 and 4

ifs_back="$IFS"             # back up IFS
IFS=$'\t'                   # set IFS to TAB
for ((i=0; i<rows; i++)); do
    j=$((i * cols))
    echo "${array[*]:$j:$cols}"
done
IFS="$ifs_back"             # restore IFS

輸出:

1       2       3       4
5       6       7       8

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM