Print second last column/field in awk

后端 未结 9 1963
野趣味
野趣味 2020-11-29 16:58

I want to print the second last column or field in awk. The number of fields is variable. I know that I should be able to use $NF but not sure how it can be use

9条回答
  •  死守一世寂寞
    2020-11-29 17:34

    You weren't far from the result! This does it:

    awk '{NF--; print $NF}' file
    

    This decrements the number of fields in one, so that $NF contains the former penultimate.

    Test

    Let's generate some numbers and print them on groups of 5:

    $ seq 12 | xargs -n5
    1 2 3 4 5
    6 7 8 9 10
    11 12
    

    Let's print the penultimate on each line:

    $ seq 12 | xargs -n5 | awk '{NF--; print $NF}'
    4
    9
    11
    

提交回复
热议问题