2

I have a program that prints out the following:

bash-3.2$ ./drawgrid
0
1 1 0 
1 1 0 
0 0 0 
1
0 1 1 
0 1 1 
0 0 0 
2
0 0 0 
1 1 0 
1 1 0 
3
0 0 0 
0 1 1 
0 1 1 

Is it possible to pipe the output of this command such that I get all the 3x3 matrices (together with their number) displayed on a table, for example a 2x2 like this?

0       1
1 1 0   0 1 1
1 1 0   0 1 1
0 0 0   0 0 0 
2       3
0 0 0   0 0 0 
1 1 0   0 1 1
1 1 0   0 1 1

I tried searching, and came across the column command, but I did not figure it out.

Thank you

3 Answers 3

1

You can use pr -2T to get the following output, which is close to what you expected:

0                                   2
1 1 0                               0 0 0
1 1 0                               1 1 0
0 0 0                               1 1 0
1                                   3
0 1 1                               0 0 0
0 1 1                               0 1 1
0 0 0                               0 1 1
Sign up to request clarification or add additional context in comments.

Comments

1

You could use an awk script:

NF == 1 {
    if ($NF % 2 == 0) {
        delete line
        line[1]=$1
        f=1
    } else {
        print line[1]"\t"$1
        f=0
    }
    n=1
}
NF > 1 {
    n++
    if (f)
        line[n]=$0
    else
        print line[n]"\t"$0
}

And pipe to it like so:

$ ./drawgrid | awk -f 2x2.awk
0       1
1 1 0   0 1 1 
1 1 0   0 1 1 
0 0 0   0 0 0 
2       3
0 0 0   0 0 0 
1 1 0   0 1 1 
1 1 0   0 1 1

Comments

0

You can get exactly what you expect with a short bash script and a little array index thought:

#!/bin/bash

declare -a idx
declare -a acont
declare -i cnt=0
declare -i offset=0

while IFS=$'\n'; read -r line ; do

    [ ${#line} -eq 1 ] && { idx+=( $line ); ((cnt++)); }
    [ ${#line} -gt 1 ] && { acont+=( $line );((cnt++)); }

done

for ((i = 0; i < ${#idx[@]}; i+=2)); do

    printf "%4s%8s\n" ${idx[i]} ${idx[i+1]} 
    for ((j = offset; j < offset + 3; j++)); do
        printf " %8s%8s\n" ${acont[j]} ${acont[j+3]} 
    done
    offset=$((j + 3))

done

exit 0

Output

$ bash array_cols.sh <dat/cols.txt
   0       1
   1 1 0   0 1 1
   1 1 0   0 1 1
   0 0 0   0 0 0
   2       3
   0 0 0   0 0 0
   1 1 0   0 1 1
   1 1 0   0 1 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.