using awk command I tried to print the upper triangle of a matrix
使用awk命令我试图打印矩阵的上三角形
awk '{for (i=1;i<=NF;i++) if (i>=NR) printf $i FS "\n"}' matrix
but the output is shown as a single row
但输出显示为单行
3 个解决方案
#1
2
Consider this sample 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
1
This might work for you (GNU sed):
这可能适合你(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 those lines that have been processed and for each current line remove those many fields from the front of the current line.
使用保留空间作为已处理的行的计数器,并且对于每个当前行,从当前行的前面删除那些许多字段。
N.B. The counter is set following the printing of the current line otherwise the first line would be minus the first field.
注:在打印当前行之后设置计数器,否则第一行将减去第一个字段。
On reflection an alternative/more elegant solution is:
经过反思,另一种/更优雅的解决方案是:
sed -r '1!G;h;:a;s/^\S+\s*(.*)\n.*/\1/;ta' file
And to print the upper-left triangle:
并打印左上角三角形:
sed -r '1!G;h;:a;s/^([^\n]*)\S+[^\n]*(.*)\n.*/\1\2/;ta' file
#3
0
$ awk '{for (i=NR;i<=NF;i++) printf "%s%s",$i,(i<NF?FS:RS)}' file
1 2 3
5 6
9
#1
2
Consider this sample 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
1
This might work for you (GNU sed):
这可能适合你(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 those lines that have been processed and for each current line remove those many fields from the front of the current line.
使用保留空间作为已处理的行的计数器,并且对于每个当前行,从当前行的前面删除那些许多字段。
N.B. The counter is set following the printing of the current line otherwise the first line would be minus the first field.
注:在打印当前行之后设置计数器,否则第一行将减去第一个字段。
On reflection an alternative/more elegant solution is:
经过反思,另一种/更优雅的解决方案是:
sed -r '1!G;h;:a;s/^\S+\s*(.*)\n.*/\1/;ta' file
And to print the upper-left triangle:
并打印左上角三角形:
sed -r '1!G;h;:a;s/^([^\n]*)\S+[^\n]*(.*)\n.*/\1\2/;ta' file
#3
0
$ awk '{for (i=NR;i<=NF;i++) printf "%s%s",$i,(i<NF?FS:RS)}' file
1 2 3
5 6
9