如何使用包含逗号的awk编写csv文件

时间:2013-03-20 04:02:20

标签: linux csv awk

我有这样的文件

field1****This is, sample text ", here and there"@@@@field2****This is, sample text ", here and there"@@@@field3****This is, sample text ", here and there"@@@@

**** is the field separator

@@@@ is the record separator

我想要像这样的csv

field1, "This is, sample text ", here and there""

这样我就可以在microsoft excel中打开并在两列中显示

1 个答案:

答案 0 :(得分:1)

$ cat file
field1****This is, sample text ", here and there"@@@@field2****This is, sample text ", here and there"@@@@field3****This is, sample text ", here and there"@@@@

$ gawk -F'\\*\\*\\*\\*' -v OFS=', ' -v RS='@@@@\n?' '{$2="\"" $2 "\""}1' file
field1, "This is, sample text ", here and there""
field2, "This is, sample text ", here and there""
field3, "This is, sample text ", here and there""

$ gawk -F'\\*\\*\\*\\*' -v OFS=', ' -v RS='@@@@\n?' '{for (i=1;i<=NF;i++) $i="\"" $i "\""}1' file
"field1", "This is, sample text ", here and there""
"field2", "This is, sample text ", here and there""
"field3", "This is, sample text ", here and there""