如何匹配txt文件中的3行并提取中间行的字符串
How to match 3 lines in txt file and extract string in the middle line
我想使用 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 行以及中间的许多行。
正则表达式通常不能很好地替代 context-sensitive multi-line 解析器。
鉴于文档格式,我简单写一个:
$grabLine = $false
switch -File($filename1){
' 1' {
$grabLine = $true
}
' 40' {
$grabLine = $false
}
default{
if($grabLine){
$_
# break here if you only need one line
}
}
}
您可以使用正则表达式来完成:
$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
我想使用 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 行以及中间的许多行。
正则表达式通常不能很好地替代 context-sensitive multi-line 解析器。
鉴于文档格式,我简单写一个:
$grabLine = $false
switch -File($filename1){
' 1' {
$grabLine = $true
}
' 40' {
$grabLine = $false
}
default{
if($grabLine){
$_
# break here if you only need one line
}
}
}
您可以使用正则表达式来完成:
$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