awk用引号连接csv列

时间:2018-03-08 11:17:08

标签: awk

我想连接一个csv文件的两列。我对csv的引用有somme问题。

"column one","column two","column three"
"A","1","A1"
"B","2","B2"
"C","3","C3"

我使用此命令行:

awk -F, '{$2=$3" - "$x;for(i=1;i<=NF;i++)if(i!=x)f=f?f FS $i:$i;print f;f=""}' x=3 file.csv

结果是:

"column one","column two"
"A","1" - "A1"
"B","2" - "B2"
"C","3" - "C3"

我想删除第二列“3 **” - “** C3”

的内部引号

3 个答案:

答案 0 :(得分:1)

使用GNU awk

$ awk -F, -v OFS=, 'NR==1{NF--} {print gensub(/","/," - ",2)}' file

"column one","column two"
"A","1 - A1"
"B","2 - B2"
"C","3 - C3"
第一行

,删除最后一个字段。否则用连字符替换带引号的逗号。

答案 1 :(得分:0)

Awk 解决方案:

awk 'BEGIN{ FS=OFS="\042,\042" }{ $2=$2" - "$3; NF=2 }1' file.csv

输出:

"A","1 - A1"
"B","2 - B2"
"C","3 - C3"

答案 2 :(得分:0)

Gnu sed:

kent$  cat f
"A","1","A1"
"B","2","B2"
"C","3","C3"

kent$  sed 's/","/ - /2' f
"A","1 - A1"
"B","2 - B2"
"C","3 - C3"

测试:

{{1}}