我需要使用"FPAT“或gawk的等效函数"patsplit”。但是在CentOs服务器上安装的gawk版本似乎是3.1.5。
我尝试使用以下命令更新gawk:
yum update gawk;服务器显示:"No Packages marked for Update“
我还尝试用以下命令重新安装gawk:
yum install gawk;服务器输出:"Package gawk-3.1.5-15.el5.x86_64已安装且最新版本“
我需要gawk 4.0或更高版本才能使用这些FPAT或patsplit。以及为什么我需要使用它们?我正在尝试处理一个CSV文件,似乎CSV文件有可选的引号和嵌入的逗号。
示例:
如下所示的csv行:
this,is,a,"csv,with,embedded coma"我需要像这样拆分字段:
this
is
a
"csv,with,embedded comma"下面是gawk代码:
awk '{patsplit("this,is,a,\"csv,with,embedded comma\"",a,"([^,]*)|(\"([^\"]|\"\")+\"[^,]*)",seps); for(i=0;i<length(a);i++) print a[i];}';有没有人能帮我一下?
发布于 2013-05-05 07:31:40
尝试在您的管道中使用csvquote,以使awk更容易解释数据。这是我编写的一个脚本,它用非打印字符替换带引号的字段中的逗号,然后恢复它们。
因此,如果您的awk命令最初是这样的:
awk -F, '{print $3 "," $5}' inputfile.csv..。它可以使用csv引用的分隔符,如下所示:
csvquote inputfile.csv | awk -F, '{print $3 "," $5}' | csvquote -u有关代码和更多文档,请参阅https://github.com/dbro/csvquote
发布于 2013-01-02 22:13:49
我认为我们可以使用match()来获取字段。
代码如下:
awk '{ $0=$0","
while($0) {
match($0,/ *"[^"]*" *,|[^,]*,/)
field=substr($0,RSTART,RLENGTH)
gsub(/,$/,"",field)
print field
$0=substr($0,RLENGTH+1)
}}' file使用您的输入示例进行测试:
kent$ echo 'this,is,a,"csv,with,embedded coma"'|awk '{
$0=$0","
while($0) {
match($0,/ *"[^"]*" *,|[^,]*,/)
field=substr($0,RSTART,RLENGTH)
gsub(/,$/,"",field)
print field
$0=substr($0,RLENGTH+1)
}}'
this
is
a
"csv,with,embedded coma"发布于 2013-01-03 04:44:36
例如:
$ cat file
this,is,a,"csv,with,embedded coma",and,here,"is,another",one
and,here,"is,another,line"
$
$ awk 'BEGIN{FS=OFS="\""}{for (i=1;i<=NF;i+=2) gsub(/,/,";",$i)}1' file
this;is;a;"csv,with,embedded coma";and;here;"is,another";one
and;here;"is,another,line"如果您不喜欢“;”作为字段分隔符,可以选择其他的分隔符,比如控制字符,或者这里有一个使用换行符作为FSs,使用空行作为RSs的示例:
$ awk 'BEGIN{FS=OFS="\""; ORS="\n\n"}{for (i=1;i<=NF;i+=2) gsub(/,/,"\n",$i)}1' file
this
is
a
"csv,with,embedded coma"
and
here
"is,another"
one
and
here
"is,another,line"
$ awk 'BEGIN{FS=OFS="\""; ORS="\n\n"}{for (i=1;i<=NF;i+=2) gsub(/,/,"\n",$i)}1' file |
awk -F'\n' -v RS= '{for (i=1;i<=NF;i++) print NR,i,"<" $i ">"}'
1 1 <this>
1 2 <is>
1 3 <a>
1 4 <"csv,with,embedded coma">
1 5 <and>
1 6 <here>
1 7 <"is,another">
1 8 <one>
2 1 <and>
2 2 <here>
2 3 <"is,another,line">只有当你有嵌入的换行符或嵌入的转义双引号时,它才变得棘手。
https://stackoverflow.com/questions/14119260
复制相似问题