【问题标题】:Add empty columns at the end of a CSV file在 CSV 文件末尾添加空列
【发布时间】:2013-10-16 05:31:35
【问题描述】:

我有一个包含数字和字符串值的 .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 对此问题的任何输入.

【问题讨论】:

  • 您可以控制 CSV 的生成吗?如果是这样,您可以使用不同的字段分隔符(如 |)吗?
  • 文件末尾有很多空格。
  • @Nirk 我不生成 CSV。我是从一位客户那里得到的。
  • @Jotne 后面的空格是由于本论坛的代码示例规则,我的意思是在代码示例中创建一个新行。我必须留出两个空格来移动下一行中的数据。
  • 如果您想将双引号 " 作为一个文件进行威胁,那么您需要进行认真的编程。谷歌搜索 csv 和 awk。在 excel 中导入文件并在那里修复它可能会更快。

标签: linux csv sed awk double-quotes


【解决方案1】:
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,

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

【讨论】:

    【解决方案2】:

    如果您的输入始终包含 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,,,,,,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2016-09-10
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多