Print second last column/field in awk

后端 未结 9 1960
野趣味
野趣味 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条回答
  •  萌比男神i
    2020-11-29 17:36

    Perl solution similar to Chris Kannon's awk solution:

    perl -lane 'print $F[$#F-1]' file
    

    These command-line options are used:

    • n loop around every line of the input file, do not automatically print every line

    • l removes newlines before processing, and adds them back in afterwards

    • a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

    • e execute the perl code

    The @F autosplit array starts at index [0] while awk fields start with $1.
    $#F is the number of elements in @F

提交回复
热议问题