首页 > 解决方案 > 如何匹配txt文件中的3行并在中间行提取字符串

问题描述

使用 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 行以及介于两者之间的许多行。

标签: powershellmatchselect-string

解决方案


您可以使用正则表达式来做到这一点:

$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

推荐阅读