parse a csv file that contains commans in the fields with awk

后端 未结 4 916
独厮守ぢ
独厮守ぢ 2021-02-05 10:47

i have to use awk to print out 4 different columns in a csv file. The problem is the strings are in a $x,xxx.xx format. When I run the regular awk command.

awk -         


        
4条回答
  •  日久生厌
    2021-02-05 11:17

    I think what you're saying is that you want to split the input into CSV fields while not getting tripped up by the commas inside the double quotes. If so...

    First, use "," as the field separator, like this:

    awk -F'","' '{print $1}'
    

    But then you'll still end up with a stray double-quote at the beginning of $1 (and at the end of the last field). Handle that by stripping quotes out with gsub, like this:

    awk -F'","' '{x=$1; gsub("\"","",x); print x}'
    

    Result:

    echo '"abc,def","ghi,xyz"' | awk -F'","' '{x=$1; gsub("\"","",x); print x}'
    
    abc,def
    

提交回复
热议问题