[colug-432] Printing Next to Last Field

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Wed Oct 14 18:25:54 EDT 2015


On Wed, 14 Oct 2015 17:59:33 -0400, jep200404 at columbus.rr.com wrote:

> Compare the two following filter chains for printing the last field on a line.
> Which one would you choose? Why?
> 
>     ... | rev | awk '{print $1}' | rev
>     ... | awk '{print $NF}'

Similarly for next to last field:

    ... | rev | awk '{print $2}' | rev
    ... | awk '{print $(NF-1)}'

> What are the interesting edge cases?

    [jep at main ~]$ cat fo
    three tres tree
    to two
    one
    
    [jep at main ~]$ cat fo | rev | awk '{print $1}' | rev
    tree
    two
    one
    
    [jep at main ~]$ cat fo | awk '{print $NF}'
    tree
    two
    one
    
    [jep at main ~]$ cat fo | rev | awk '{print $2}' | rev
    tres
    to
    
    
    [jep at main ~]$ cat fo | awk '{print $(NF-1)}'
    tres
    to
    one
    awk: cmd. line:1: (FILENAME=- FNR=4) fatal: attempt to access field -1
    [jep at main ~]$ 

No difference for the last field, 
but differences for the next to last field.
"cat fo | rev | awk '{print $2}' | rev" prints nothing,
when "cat fo | awk '{print $(NF-1)}'" prints "one".
"cat fo | rev | awk '{print $2}' | rev" prints nothing,
when "cat fo | awk '{print $(NF-1)}'" complains.


More information about the colug-432 mailing list