你如何用gawk解析csv文件?简单地设置FS =“,”是不够的,因为带有逗号的引用字段将被视为多个字段.
使用FS =“,”的示例不起作用:
- one,two,"three,four",five
- "six,seven",eight,"nine"
gawk脚本:
- BEGIN { FS="," }
- {
- for (i=1; i<=NF; i++) printf "field #%d: %s\n",i,$(i)
- printf "---------------------------\n"
- }
输出不好
- field #1: one
- field #2: two
- field #3: "three
- field #4: four"
- field #5: five
- ---------------------------
- field #1: "six
- field #2: seven"
- field #3: eight
- field #4: "nine"
- ---------------------------
所需输出:
- field #1: one
- field #2: two
- field #3: "three,four"
- field #4: five
- ---------------------------
- field #1: "six,seven"
- field #2: eight
- field #3: "nine"
- ---------------------------
简短的答案是“如果CSV包含尴尬的数据,我不会使用gawk来解析CSV”,那么“尴尬”是指CSV字段数据中的逗号.
下一个问题是“你还要做什么其他处理”,因为这会影响你使用什么方法.
我可能会使用Perl和Text :: CSV或Text :: CSV_XS模块来读取和处理数据.记住,Perl最初是作为一个awk和sed的杀手部分编写的 – 因此,a2p和s2p程序仍然与Perl一起分发,将awk和sed脚本分别转换为Perl.