linux awk命令取矩阵对角线元素

1、取正对角线

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1 D E
2 s d
3 d c
root@PC1:/home/test# awk '{print $NR}' a.txt   ## 取矩阵对角线元素,正对角线
1
s
c

 

2、取逆对角线

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1 D E
2 s d
3 d c
root@PC1:/home/test# awk '{for(i = NF; i >= 1; i--) printf("%s ", $i); printf("\n")}' a.txt | awk '{print $NR}'  ## 取逆对角线元素
E
s
3
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1 D E
2 s d
3 d c
root@PC1:/home/test# awk '{print $(NF + 1 - NR)}' a.txt   ## 取逆对角线元素
E
s
3

 

posted @ 2022-01-23 21:40  小鲨鱼2018  阅读(82)  评论(0编辑  收藏  举报