AWK to use multiple spaces as delimiter

后端 未结 2 1490
甜味超标
甜味超标 2021-02-19 01:58

I am using below command to join two files using first two columns.

awk \'NR==FNR{a[$1,$2]=substr($0,3);next} ($1,$2) in a{print $0, a[$1,$2] > \"br0102_3.tx         


        
相关标签:
2条回答
  • 2021-02-19 02:23

    You are using fixed width fields so you should be using gnu awk FIELDWIDTHS (or similar) to separate the fields, e.g. if the 2nd field is the 15 chars from char 8 to char 23 inclusive in this file:

    $ cat file
    abc    def ghi        klm
    AAAAAAAB C D E F G H IJJJJ
    abc       def ghi     klm
    
    $ awk -v FIELDWIDTHS="7 15 4" '{print "<" $2 ">"}' file
    <def ghi        >
    <B C D E F G H I>
    <   def ghi     >
    

    Any solution that relies on a certain number of spaces between fields will fail when you have 1 or zero spaces between your fields.

    If you want to strip leading/trailing blanks from your target field(s):

    $ awk -v FIELDWIDTHS="7 15 4" '{gsub(/^\s+|\s+$/,"",$2); print "<" $2 ">"}' file
    <def ghi>
    <B C D E F G H I>
    <def ghi>
    
    0 讨论(0)
  • 2021-02-19 02:41

    awk supports a regular expression as the value of FS so you can specify a regular expression that matches at least two spaces. Something like -F '[[:space:]][[:space:]]+'.

    $ awk '{print NF}' File2
    4
    3
    4
    
    $ awk -F '[[:space:]][[:space:]]+' '{print NF}' File2
    3
    3
    3
    
    0 讨论(0)
提交回复
热议问题