【问题标题】:How to match 3 lines in txt file and extract string in the middle line如何匹配txt文件中的3行并在中间行提取字符串
【发布时间】:2019-06-19 11:26:50
【问题描述】:

使用 Powershell 我想从文本文件中提取一个值,该值位于与模式匹配的两行之间。

我正在尝试匹配 3 行,第 1 行和第 3 行将始终相同:

1st: '  1'
2nd: trying to read... always 2-4 characters
3rd: ' 40'

在很多情况下第 1 行和第 3 行应该与此匹配。

我尝试使用以下代码。

$aa=Get-Content $filename1 -Raw
$aaa=$aa  |Where-Object { ( $_ -match '(.\s1)(?:\r\n|[\r\n])*(?:\r\n|[\r\n])(\s40)') }
$aaa

我得到了太多的输出...也许它只匹配第 1 行和第 3 行以及中间的许多行。

【问题讨论】:

    标签: powershell match select-string


    【解决方案1】:

    您可以使用正则表达式:

    $regex = [regex] '\s+1\r?\n(?<secondline>.*)\r?\n\s+40'
    $match = $regex.Match($text)
    $result = while ($match.Success) {
        $match.Groups['secondline'].Value
        $match = $match.NextMatch()
    } 
    
    $result
    

    其中$text 是您使用$text = Get-Content 'FILENAME' -Raw 读取的文件,如下所示:

      1
    trying to read... always 2-4 characters
     40
      1
    another second line
     40
      1
    the line you are interested in
     40
    

    结果是

    trying to read... always 2-4 characters
    another second line
    the line you are interested in
    

    【讨论】:

      【解决方案2】:

      正则表达式通常不能很好地替代上下文相关的多行解析器。

      鉴于文档格式,我只想写一个:

      $grabLine = $false
      
      switch -File($filename1){
        '  1' {
          $grabLine = $true
        }
        ' 40' {
          $grabLine = $false
        }
        default{
          if($grabLine){
            $_
            # break here if you only need one line 
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-08
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        相关资源
        最近更新 更多