Bash printing diagonal of any size array

后端 未结 3 1782
傲寒
傲寒 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:12
    awk '!i{i=NF}{printf "%s ",$i;i--}'
    

    EDIT: Since Ed has already exploited all the nice and proper awk solutions I'll throw in a native bash solution:

    $ cat t.sh
    #!/bin/bash
    
    while read -ra numbers; do
            : ${i:=${#numbers[@]}}
            diag+=("${numbers[--i]}")
    done < test.txt
    echo "${diag[@]}"
    

    .

    $ ./t.sh
    4 7 1 4
    
    0 讨论(0)
  • 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--}'
    
    0 讨论(0)
  • 2021-01-15 04:32
    $ awk '{print $(NF+1-NR)}' file    
    4
    7
    1
    4
    
    $ awk -v ORS=" " '{print $(NF+1-NR)}' file
    4 7 1 4 
    

    or if you want to avoid adding a space to the end of your output line and to have a terminating newline:

    $ awk '{printf "%s%s", (NR>1?FS:""), $(NF+1-NR)} END{print ""}' file
    4 7 1 4
    
    0 讨论(0)
提交回复
热议问题