0

我有一个带有数字和字符串值的 .CSV 文件(比如说命名为 file.csv)。该字符串可能包含逗号,因此它们用双引号括起来,如下所示。

column1,column2,column3,column4,column5,column6,column7  
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88  
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455  
11,22,"simple, string",77,777,333,22  

当我尝试在文件末尾添加空列时,使用以下代码

awk -F, '{NF=13}1' OFS="," file.csv > temp_file.csv

输出不符合我的要求。该代码还计算了文本限定符字段中的逗号,它们用双引号括起来。使用上述命令的文件输出cat temp_file.csv如下:

column1,column2,column3,column4,column5,column6,column7,,,,,,  
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88,  
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88  
11,22,"simple, string",77,777,333,22,,,,,  

因为我需要该字段中的字段总数为 13。非常感谢使用awk或使用任何关于此问题的输入。sed

4

2 回答 2

0
awk -F, '{sub(/ *$/,"");$0=$0 ","}1' OFS=,
column1,column2,column3,column4,column5,column6,column7,
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88,
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455,
11,22,"simple, string",77,777,333,22,

这将删除尾随空格并在末尾添加一个字段。

于 2013-10-09T04:49:03.727 回答
-1

如果您的输入始终有 7 个已发布的字段,请选择:

awk '{print $0 ",,,,,,"}' file
sed 's/$/,,,,,,/' file

或删除尾随空格:

awk '{sub(/ *$/,",,,,,,")}1' file
sed 's/ *$/,,,,,,/' file

如果您的输入文件可以有不同数量的字段,但仍然有您显示的标题行:

awk -F, 'NR==1{flds=sprintf("%*s",13-NF,""); gsub(/ /,FS,flds)} {sub(/ *$/,flds)} 1' file
column1,column2,column3,column4,column5,column6,column7,,,,,,
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88,,,,,,
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455,,,,,,
11,22,"simple, string",77,777,333,22,,,,,,
于 2013-10-09T10:51:59.720 回答