【问题标题】:Script to split comma separated text?拆分逗号分隔文本的脚本?
【发布时间】:2020-04-04 16:31:53
【问题描述】:

我正在寻找一个简单的脚本来执行以下操作:

我有两个文本列,一个有很多名称,用逗号分隔,另一个有日期,即

col 1         col2
matt, john    12/11/2019

我想将其转换为以下内容:

col1          col2
matt          12/11/2019
john          12/11/2019

这很容易做到吗?我不擅长写脚本……

【问题讨论】:

  • 我们还没有收到您的来信。我的回答解决了您的问题吗?如果是这样,请点击左侧的✓ 考虑accepting。这将帮助其他有类似问题的人更轻松地找到它。

标签: powershell scripting


【解决方案1】:

你没有说预期的输出应该是什么,所以这是为了创建一个可以轻松显示为表格或写入文件的对象数组。

# simulating the text in a Here-string.
# If your input is in a file, use 
# $text = Get-Content -Path '<THE FILE>'

$text = @"
col 1         col2
matt, john    12/11/2019
"@ -split '\r?\n'

$result = $text | Select-Object -Skip 1 |  ForEach-Object {
    $names, $date = ($_ -replace ',\s+', ',') -split '\s+', 2
    foreach ($name in $names -split ',') {
        [PsCustomObject]@{
            'col1' = $name
            'col2' = $date
        }
    }
}

结果将是一个对象数组,每个对象都有两个属性:col1col2

# Output on screen
$result

# output to CSV file
$result | Export-Csv -Path 'X:\example.csv' -NoTypeInformation

屏幕上的结果:

col1 col2      
---- ----      
matt 12/11/2019
john 12/11/2019

希望有帮助

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多