How to print last two columns using awk

后端 未结 6 1296
甜味超标
甜味超标 2021-01-29 19:16

All I want is the last two columns printed.

相关标签:
6条回答
  • 2021-01-29 19:30
    awk '{print $NF-1, $NF}'  inputfile
    

    Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"

    0 讨论(0)
  • 2021-01-29 19:38

    using gawk exhibits the problem:

     gawk '{ print $NF-1, $NF}' filename
    1 2
    2 3
    -1 one
    -1 three
    # cat filename
    1 2
    2 3
    one
    one two three
    

    I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

    http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html
    

    There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

    0 讨论(0)
  • 2021-01-29 19:46

    @jim mcnamara: try using parentheses for around NF, i. e. $(NF-1) and $(NF) instead of $NF-1 and $NF (works on Mac OS X 10.6.8 for FreeBSD awkand gawk).

    echo '
    1 2
    2 3
    one
    one two three
    ' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
    
    # output:
    # 1 2
    # 2 3
    # two three
    
    0 讨论(0)
  • 2021-01-29 19:46

    try with this

    $ cat /tmp/topfs.txt
    /dev/sda2      xfs        32G   10G   22G  32% /
    
    awk print last column
    $ cat /tmp/topfs.txt | awk '{print $NF}'
    
    awk print before last column
    $ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
    32%
    
    awk - print last two columns
    $ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
    32% /
    
    0 讨论(0)
  • 2021-01-29 19:52

    You can make use of variable NF which is set to the total number of fields in the input record:

    awk '{print $(NF-1),"\t",$NF}' file
    

    this assumes that you have at least 2 fields.

    0 讨论(0)
  • 2021-01-29 19:53

    Please try this out to take into account all possible scenarios:

    awk '{print $(NF-1)"\t"$NF}'  file
    

    or

    awk 'BEGIN{OFS="\t"}' file
    

    or

    awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file
    
    0 讨论(0)
提交回复
热议问题