【问题标题】:Search CSV file to find a specific value without specifying column name with Powershell搜索 CSV 文件以查找特定值,而无需使用 Powershell 指定列名
【发布时间】:2017-01-06 10:25:20
【问题描述】:

有没有办法逐行搜索 .CSV 文件以查找特定值,而无需指定要搜索的列名,希望在多个 .CSV 文件上运行此脚本,因此指定列名不是我的选择。

示例 PowerShell 代码:

foreach ($row in $csvFile){
    if ($row -eq/-contains $StringIWantToFind) {
        #do something with the string here
    }
}

【问题讨论】:

    标签: powershell csv


    【解决方案1】:

    如果您不关心(子)字符串在哪个列中,您可以使用通配符匹配:

    $row -like "*$StringIWantToFind*"
    

    或正则表达式匹配:

    $row -match $StringIWantToFind
    

    如果您想将值用于某事,后者可能是更好的选择,因为它通过自动变量 $matches 为您提供匹配(和子匹配):

    $StringIWantToFind = 'something (captured group) or other'
    
    foreach ($row in $csvFile) {
        if ($row -match $StringIWantToFind) {
            # do something with $matches[0] (full match) or $matches[1] (captured
            # group) here
        }
    }
    

    【讨论】:

      【解决方案2】:

      最快的方法是使用Select-String,如下所示:

      Select-String your_file.txt -Pattern 'string to find' -SimpleMatch
      

      如果你想处理结果,你可以像这样提取匹配的行:

      Select-String your_file.txt -Pattern 'xx' -SimpleMatch | Select -ExpandProperty line | % {
        # your processing here using $_
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-26
        • 2023-04-07
        相关资源
        最近更新 更多