Bash printing diagonal of any size array

后端 未结 3 1781
傲寒
傲寒 2021-01-15 03:38

So here I have the following code:

#!/bin/bash
awk \'BEGIN {f=4} {printf($f\" \"); f=f-1}\'

Which will take input such as:

         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-15 04:26

    The problem is, NF at BEGIN section is not the number of tokens on the first line. The following works:

    awk '{if (!f) f = NF; printf($f" "); f=f-1}'
    

    Edit: as per suggestions in the comments, a cleaner and safer way is:

    awk '{if (!f) f = NF; printf("%s ", $f); f--}'
    

提交回复
热议问题