Awk consider double quoted string as one token and ignore space in between

前端 未结 7 1048
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 17:26

Data file - data.txt:

ABC \"I am ABC\" 35 DESC
DEF \"I am not ABC\" 42 DESC

cat data.txt | awk \'{print $2}\'

will re

7条回答
  •  不知归路
    2020-12-15 18:16

    I've scrunched up together a function that re-splits $0 into an array called B. Spaces between double quotes are not acting as field separators. Works with any number of fields, a mix of quoted and unquoted ones. Here goes:

    #!/usr/bin/gawk -f
    
    # Resplit $0 into array B. Spaces between double quotes are not separators.
    # Single quotes not handled. No escaping of double quotes.
    function resplit(       a, l, i, j, b, k, BNF) # all are local variables
    {
      l=split($0, a, "\"")
      BNF=0
      delete B
      for (i=1;i<=l;++i)
      {
        if (i % 2)
        {
          k=split(a[i], b)
          for (j=1;j<=k;++j)
            B[++BNF] = b[j]
        }
        else
        {
          B[++BNF] = "\""a[i]"\""
        }
      }
    }
    
    {
      resplit()
    
      for (i=1;i<=length(B);++i)
        print i ": " B[i]
    }
    

    Hope it helps.

提交回复
热议问题