How to print all the columns after a particular number using awk?

后端 未结 11 690
一生所求
一生所求 2020-12-22 20:23

On shell, I pipe to awk when I need a particular column.

This prints column 9, for example:

... | awk \'{print $9}\'

How can I tell

11条回答
  •  甜味超标
    2020-12-22 21:15

    awk -v m="\x01" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'
    

    This chops what is before the given field nr., N, and prints all the rest of the line, including field nr.N and maintaining the original spacing (it does not reformat). It doesn't mater if the string of the field appears also somewhere else in the line, which is the problem with Ascherer's answer.

    Define a function:

    fromField () { 
    awk -v m="\x01" -v N="$1" '{$N=m$N; print substr($0,index($0,m)+1)}'
    }
    

    And use it like this:

    $ echo "  bat   bi       iru   lau bost   " | fromField 3
    iru   lau bost   
    $ echo "  bat   bi       iru   lau bost   " | fromField 2
    bi       iru   lau bost   
    

    Output maintains everything, including trailing spaces For N=0 it returns the whole line, as is, and for n>NF the empty string

提交回复
热议问题