我有一个变量
local= "[ 'service center','New' ]"
我使用以下 awk 代码删除了方括号和单引号,
local=gensub(/[\[\]']+/, "", "g", local);
预期的 O/P 是
local =" service center,New "
我写的代码不起作用
我需要在 csv 文件中添加两个字段。csv 字段的分隔符是comma
,有些字段在双引号内。问题是,在双引号字段内,也可能找到逗号。如何用awk拆分?
这些字段来自 mongo 导出。这些字段的位置可能会改变,
样本输入 csv,
DateTime,Dealers,Locations,CallEndTime,TotalDuration
"2018-12-27 12:19:14","Dealer1,Dealer2,Dealer3","Gujarat",,67,,
"2018-12-27 12:19:14","Dealer1,Dealer2","Gujarat,Vadodara",,100,
样本输出 csv,
DateTime,Dealers,Locations,CallEndTime,TotalDuration
"2019-01-07 11:35:42","Dealer1,Dealer2,Dealer3","Gujarat","2019-01-07 11:36:51",69,,
"2018-12-27 12:19:14","Dealer1,Dealer2","Gujarat,Vadodara","2018-12-27 12:19:14,78",
awk 代码:
BEGIN { FSOFS=","}
NR==1 {
for (i=1; i<=NF; i++) {
f[$i] = i
}
}
NR>1 {
begSecs = mktime( gensub( /[":-]/, " ", "g", $(f["DateTime"]) ) )
endSecs = begSecs + $(f["TotalDuration"])
$(f["CallEndTime"]) = strftime("%Y-%m-%d %H:%M:%S", endSecs)
}
{print}
我不想将双引号内的逗号视为 FS,我已经看到这可以使用 FPAT 来完成,但我不知道如何在此处使用它,以防万一,
BEGIN { FPAT = "([^,]*)|(\"[^\"]+\")"}
NR==1 {
for (i=1; i<=NF; i++) {
f[$i] = i
}
}
NR>1 {
begSecs = mktime( gensub(/[":-]/," ","g",$(f["DateTime"])) )
endSecs = begSecs + $(f["TotalDuration"])
$(f["CallEndTime"]) = strftime("%Y-%m-%d %H:%M:%S", endSecs)
}
{print}
我有一个awk
脚本,new.awk
:
BEGIN { FS = OFS = "," }
NR == 1 {
for (i = 1; i <= NF; i++)
f[$i] = i
}
NR > 1 {
begSecs = mktime(gensub(/[":-]/, " ", "g", $(f["DateTime"])))
endSecs = begSecs + $(f["TotalDuration"])
$(f["CallEndTime"]) = strftime("%Y-%m-%d %H:%M:%S", endSecs)
}
{ print }
我在 shell 中调用它
awk new.awk sample.csv
...但我可以看到终端的变化。如何在文件中进行就地更改,例如使用时sed -i
?