【问题标题】:Filter CSV Carriage Return过滤 CSV 回车
【发布时间】:2017-08-24 20:47:47
【问题描述】:

试图弄清楚如何过滤特定 CSV 中的项目。

CSV 内容:

ComputerName,Results
computerA      ," KB00000 is not installed 
c:\SomeTestFile Version is 2
c:\SomeTestFile Version is 11.0"
ComputerB   ,%windir%\somefile.exe is Version 1.2

我需要它首先根据第二列中的回车进行过滤,然后过滤掉不同的参数,例如“is version10”或“KB00000 is missing”。

CSV 格式的预期输出:

ComputerName,Results
computerA ,c:\SomeTestFile Version is 2
computerA ,c:\SomeTestFile Version is 11.0
ComputerB ,%windir%\somefile.exe is Version 1.2

有一个编码块。我可以导入文件但卡在过滤上。

$CSV = Import-Csv File.csv 

【问题讨论】:

  • 您的示例内容是 CSV 的实际原始内容吗(在文本编辑器中打开时)?
  • 我在这里输入了它,但如果你把它放在 csv 中,它看起来像: ComputerName,Results computerA ," KB00000 is not installed c:\SomeTestFile Version is 2 c:\SomeTestFile Version is 11.0 " ComputerB ,%windir%\somefile.exe 是 1.2 版
  • edit您的问题并复制/粘贴文本。

标签: powershell csv filtering


【解决方案1】:

使用您给定的 csv

这个脚本:

## Q:\Test\2017\08\24\SO_45870618.ps1
$FileIn  = '.\FileIn.Csv'
$FileOut = '.\FileOut.Csv'

$Csv = Import-Csv $FileIn
$Csv

$CsvNew = ForEach ($Row in $Csv) {
    If (!($Row.ComputerName)){
        If ($Last) {$Row.ComputerName = $Last}
    }
    $Last = $Row.ComputerName
    ForEach ($line in ($Row.Results -Split('\r?\n')) ){
        If ($line -NotMatch '^\s*KB\d+\s+is'){
            [PSCustomObject]@{ComputerName = $Last.Trim()
                              Results = $line}
        }
    }
}
"------------"
$CsvNew 
$CsvNew | Export-Csv $FileOut -NoTypeInformation

会有这样的输出:

> Q:\Test\2017\08\24\SO_45870618.ps1

ComputerName Results
------------ -------
computerA     KB00000 is not installed ...
ComputerB    %windir%\somefile.exe is Version 1.2
------------
computerA    c:\SomeTestFile Version is 2
computerA    c:\SomeTestFile Version is 11.0
ComputerB    %windir%\somefile.exe is Version 1.2

生成的 FileOut.csv:

> gc .\FileOut.Csv
"ComputerName","Results"
"computerA","c:\SomeTestFile Version is 2"
"computerA","c:\SomeTestFile Version is 11.0"
"ComputerB","%windir%\somefile.exe is Version 1.2"

【讨论】:

  • 不幸的是,我没有得到相同的输出。它没有删除 ComputerA 的结果中的回车。 gc c:\temp\FileOut.csv "ComputerName","Results" "computerA "," KB00000 未安装 c:\SomeTestFile 版本为 2 c:\SomeTestFile 版本为 11.0" "ComputerB ","%windir%\somefile .exe 是版本 1.2"
  • 确实注意到我的Provided your csv looks like了吗?请Edit您的问题包含您的真实 csv。不要把它放在评论中。
  • 更新了有问题的 CSV,并直接从记事本中发布。谢谢
  • 将脚本改编为 csv 并添加了 Trim 以去除 ComputerName 的尾随空格。
  • 太棒了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多