- 论坛徽章:
- 15
|
本帖最后由 rdcwayx 于 2014-03-24 13:09 编辑
谈一下如果方便的处理csv格式的文件,只适用于GNU awk 4 以上版本
假设存在以下的csv文件(逗号分隔值),内容为如下格式:- Robbins,Arnold,"1234 A Pretty Street, NE",MyTown,MyState,12345-6789,USA
复制代码 注意,其中的字段("1234 A Pretty Street, NE")中包含了一个“,”,传统的FS=","来分隔域就会出错,地址会被拆分成两部分:- 1234 A Pretty Street 和 NE
复制代码 这不是我们想要的结果。
针对这样的场景,可以使用内置变量FPAT来解决问题。FPAT的值是一个正则表达式,该正则表达式描述了每一个域的内容。- FPAT = "([^,]+)|(\"[^\"]+\")"
复制代码 上面的FPAT表示,每个域或者是不包含","的字符串,或者是由一对双引号括起来的字符串。
因此,我们可以这样来解决:
复制代码- BEGIN {
- FPAT = "([^,]+)|(\"[^\"]+\")"
- }
- {
- print "NF = ", NF
- for (i = 1; i <= NF; i++) {
- printf("$%d = <%s>\n", i, $i)
- }
- }
复制代码 这个是运行结果- $ gawk -f simple-csv.awk addresses.csv
- NF = 7
- $1 = <Robbins>
- $2 = <Arnold>
- $3 = <"1234 A Pretty Street, NE">
- $4 = <MyTown>
- $5 = <MyState>
- $6 = <12345-6789>
- $7 = <USA>
复制代码 第三个字段(含逗号)作为一个域了。
再进一步,如果不希望有双引号,- if (substr($i, 1, 1) == "\"") {
- len = length($i)
- $i = substr($i, 2, len - 2) # Get text within the two quotes
- }
复制代码 参考: https://www.gnu.org/software/gaw ... ing-By-Content.html
注意:这个FPAT设置有个限制,不能处理双引号里含换行符的情况。比如这个例子: http://bbs.chinaunix.net/thread-4132643-1-1.html- NOTE: Some programs export CSV data that contains embedded newlines between the double quotes. gawk provides no way to deal with this. Since there is no formal specification for CSV data, there isn't much more to be done; the FPAT mechanism provides an elegant solution for the majority of cases, and the gawk maintainer is satisfied with that.
复制代码 |
评分
-
查看全部评分
|