我有一个包含数字和字符串值的 .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
对此问题的任何输入。
最佳答案
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,
这会删除尾随空格并在末尾添加一个字段。
关于linux - 在 CSV 文件末尾添加空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262174/