How can I print the top triangle of the matrix

using awk command I tried to print the top triangle of the matrix

awk '{for (i=1;i<=NF;i++) if (i>=NR) printf  $i FS "\n"}' matrix

but the output is displayed as a single line

+4
source share
3 answers

Consider this matrix:

$ cat matrix
1 2 3
4 5 6
7 8 9

To print the upper right triangle:

$ awk '{for (i=1;i<=NF;i++) printf "%s%s",(i>=NR)?$i:" ",FS; print""}' matrix
1 2 3 
  5 6 
    9 

Or:

$ awk '{for (i=1;i<=NF;i++) printf "%2s",(i>=NR)?$i:" "; print""}' matrix
 1 2 3
   5 6
     9

To print the upper left triangle:

$ awk '{for (i=1;i<=NF+1-NR;i++) printf "%s%s",$i,FS; print""}' matrix
1 2 3 
4 5 
7 

Or:

$ awk '{for (i=1;i<=NF+1-NR;i++) printf "%2s",$i; print""}' matrix
 1 2 3
 4 5
 7
+2
source

This may work for you (GNU sed):

sed -r ':a;n;H;G;s/\n//;:b;s/^\S+\s*(.*)\n.*/\1/;tb;$!ba' file

Use the hold space as a counter for the lines that have been processed, and for each current line, remove these many fields from the front of the current line.

NB The counter is set after printing the current line, otherwise the first line will be minus the first field.

/ :

sed -r '1!G;h;:a;s/^\S+\s*(.*)\n.*/\1/;ta' file

:

sed -r '1!G;h;:a;s/^([^\n]*)\S+[^\n]*(.*)\n.*/\1\2/;ta' file
+1
$ awk '{for (i=NR;i<=NF;i++) printf "%s%s",$i,(i<NF?FS:RS)}' file
1 2 3
5 6
9
0

All Articles