How do I get only the diagonal with awk?

Asked 2 years ago, Updated 2 years ago, 79 views

 1 2 3
4 5 6
7 8 9

When there is data (aa.txt),

under the constraint of using awk only. How do I get 1,5,9 (or 3,5,7) diagonally?
My name is

awk'NR==i{print$i}'aa.txt

I thought I could do it if I looped, but I couldn't do it well

awk

2022-09-30 21:17

2 Answers

awk'{print$NR}'aa.txt
 awk'{print$(NF-NR+1)}'aa.txt

NR is the built-in variable that substitutes the number (several lines from the top) from the beginning of the line being processed.

NF is an embedded variable that substitutes the number of fields (columns) in the row being processed.

$ is an operator that refers to a field and is often used as $1 (=first column) or $2 (=second column), but you can also give an expression in the form $(expression).(*The first code omitted ())


2022-09-30 21:17

$NR...terrible

awk'{(i=NR%NF)?0:i=NF;print$i;}'aa.txt
awk'{(i=NR%NF)?i=NF-i+1:i=1;print$i;}'aa.txt 


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.