user545642
user545642

Reputation: 113

How to print specific rows of arrays using Bash?

I currently am working with a matrix in bash. I have, say, a 2x4 matrix inside a file:

1    2    3    4
5    6    7    8

I have read from this file, and have stored all of these elements inside an array, such as:

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

Next, I piped my echo output so that the spaces change to tabs:

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

My question now is, I want to have a NEW-LINE after every four elements printed; in other words, is it possible for me to print out the array line-by-line, or row-by-row?

EDIT Here is what I have in my actual code:

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.

Here is what is the desired output:

1    2    3    4
5    6    7    8

Here is what is inside my array:

(1 2 3 4 5 6 7 8)

Upvotes: 0

Views: 780

Answers (2)

tshiono
tshiono

Reputation: 22042

One possible (ugly) solution would be to store the size of the matrix in separate variables rows and cols. Please try the following:

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

The output:

1       2       3       4
5       6       7       8

Hope this helps.

Upvotes: 1

Gordon Davisson
Gordon Davisson

Reputation: 125968

Try this:

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

The format string has four field specifiers (all %s -- just plain strings) separated by \t (tab) and ending with \n (newline), it'll print the array elements four at a time in that format.

Upvotes: 1

Related Questions