【问题标题】:How do I add a line feed (new line) in a csv file (powershell)如何在 csv 文件(powershell)中添加换行符(新行)
【发布时间】:2021-10-07 09:28:18
【问题描述】:

我有一个应该包含许多记录的大型 csv 文件。但是,由于某种原因,没有换行符或新记录分隔符,以便能够单独处理各种记录(例如通过将它们导入到 excel)*。有什么方法(例如使用 windows powershell)可以在 csv 文件中的给定字段之前添加换行符?例如,假设我们有一个包含内容的输入 csv 文件:

data1,data2,data3,data4,data5,data6,data7,data8,data9,data10;data11;data12

请求是获取这样的输出 csv(因此每条记录应包含 3 个单元格/字段....但这应该是可配置的):

data1,data2,data3
data4,data5,data6
data7,data8,data9,
data10,data11,data12

以上示例仅用于说明。考虑到我的真实案例包含我需要以某种方式组织的大量数据字段。 非常感谢您的每一个回复

*实际上,我故意从源数据中删除了每个新的换行符。我这样做是为了摆脱一些不需要的换行符和其他格式字符(\t 等),这些字符存在于特定单元格中,并且完全弄乱了数据集的结构。但是,这样我也丢失了所需的换行符 \n 。现在我想把它们加回去,选择它们应该在的正确位置。

附言由于我对 powershell 或一般脚本非常陌生,如果我提出一个明显或微不足道的问题,我很抱歉.....

【问题讨论】:

  • 乱七八糟的 csv 文件还有标题吗?你没有原始文件的副本吗?字段是否被引用?你为什么首先删除空格?

标签: powershell csv


【解决方案1】:

您可以通过计算相对列偏移量来“环绕”X 列中的任意数量的值:$index % $columnWidth

我建议为此编写一个小函数,例如:

function ConvertTo-TabularCollection {
  param(
    [Parameter(Mandatory, ValueFromPipeline)]
    [string[]]$Data,

    [Parameter(Mandatory)]
    [string[]]$ColumnNames
  )

  begin {
    # Calculate table width and prepare list to collect input data
    $width = $columnNames.Length
    $values = [System.Collections.Generic.List[string]]::new()
  }

  process {
    # Copy any input to our `$values` list
    $values.AddRange($Data)
  }

  end {
    # Time to process all the input values we've collected
    for($i = 0; $i -lt $values.Count; $i++){
      # use the modulo operator to calculate the relative column offset
      $offset = $i % $width

      if($offset -eq 0){
        # We're about to process the first column of a new row, create an empty dictionary to hold the column values
        $properties = [ordered]@{}
      }

      # Pick the next available value and show it into the appropriate column
      $properties[$columnNames[$offset]] = $values[$i]

      if($offset -eq ($width - 1)){
        # We've reached the last column, output object and clear previous column values collected
        [pscustomobject]$properties
        $properties = $null
      }
    }

    # Test if there is a (partial) row trailing, output object
    if($properties){
      [pscustomobject]$properties
    }
  }
}

现在您可以根据需要转换数据:

PS ~> $data = 'data1,data2,data3,data4,data5,data6,data7,data8,data9,data10,data11,data12' -split ','
PS ~> $data |ConvertTo-TabularCollection -ColumnNames col1,col2,col3

col1   col2   col3
----   ----   ----
data1  data2  data3
data4  data5  data6
data7  data8  data9
data10 data11 data12

【讨论】:

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