linux - 在 CSV 文件末尾添加空列

标签 linux csv sed awk double-quotes

我有一个包含数字和字符串值的 .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。非常感谢使用 awksed 对此问题的任何输入。

最佳答案

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/

相关文章:

c - 从调用自身的 ptrace 分离

linux - 向 CSV 文件中的所有行添加 2 小时 - CentOS

shell - sed命令替换空格和:之间的数字

bash - 命令输出 > sed 在特定字符串后替换

linux - 使用 sed 删除 _ 和 - 字符

linux - xen 使用命令行创建新虚拟机

c++ - 如何获取使用 QProcess 调用的程序的返回标准输出?

linux - 是否有 malloc 变体在调用 `free()` 时将 block 清零?

Python:CSV - 如果其他列足够大,则打印列的值

sql - 返回xdmp :sql() values in CSV format XQuery