【问题标题】:Search pattern in directory and extract string from files using PowerShell在目录中搜索模式并使用 PowerShell 从文件中提取字符串
【发布时间】:2019-06-18 15:50:36
【问题描述】:

我有近 400 个 .sql 文件,我需要在其中搜索特定模式并输出结果。

例如

*file1.sql

select * from mydb.ops1_tbl from something1 <other n lines>

*file2.sql

select * from mydb.ops2_tbl from something2 <other n lines>

*file3.sql

select * from mydb.ops3_tbl ,mydb.ops4_tbl where a = b <other n lines>

预期结果

file1.sql mydb.ops1_tbl

file2.sql mydb.ops2_tbl

file3.sql mydb.ops3_tbl mydb.ops4_tbl

powershell 中的以下脚本 - 能够获取文件名

Get-ChildItem -Recurse -Filter *.sql|Select-String -pattern "mydb."|group path|select name

powershell 中的以下脚本 - 能够获取行

Get-ChildItem -Recurse -Filter *.sql | Select-String -pattern "mydb." |select line

我需要上述格式,有人对此有任何指示吗?

【问题讨论】:

    标签: regex powershell scripting


    【解决方案1】:
    1. 您需要转义正则表达式中的点以匹配带有反斜杠的文字点\.
    2. 要获取一行上的所有匹配项,请使用参数-AllMatches
    3. 你需要一个更好的正则表达式来匹配 mydb 字符串到下一个空格
    4. 使用 ForEach-Object 迭代 Select-string 结果

    一个班轮:

    Get-ChildItem -Recurse -Filter *.sql|Select-String -pattern "mydb\.[^ ]+" -Allmatches|%{$_.path+" "+($_.Matches|%{$_.value})}
    

    分手

    Get-ChildItem -Recurse -Filter *.sql|
        Select-String -Pattern "mydb\.[^ ]+" -Allmatches | ForEach-Object{
            $_.path+" "+($_.Matches|ForEach-Object{$_.value})
        }
    

    样本输出:

    Q:\Test\2019\01\24\file1.sql mydb.ops1_tbl
    Q:\Test\2019\01\24\file2.sql mydb.ops2_tbl
    Q:\Test\2019\01\24\file3.sql mydb.ops3_tbl mydb.ops4_tbl
    

    如果您不想要像 Expected result 这样的完整路径(尽管您正在递归),
    $_.path 替换为(Split-Path $_.path -Leaf)

    【讨论】:

      【解决方案2】:

      首先,将文件查询的结果提取到一个数组中,然后对其进行迭代并使用正则表达式匹配提取文件内容:

      $files = Get-ChildItem -Recurse -Filter *.sql|Select-String -pattern "mydb."|group path|select name
      foreach ($file in $files)
      {
          $str = Get-Content -Path $file.Name
          $matches = ($str | select-string -pattern "mydb\.\w+" -AllMatches).Matches.Value
      
          [console]::writeline("{0:C} {1:C}", $file.Name, [string]::Join(' ', $matches) ) 
      }
      

      我使用 .NET WriteLine 函数输出结果仅用于演示目的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-22
        • 2021-11-24
        相关资源
        最近更新 更多