PowerShell:选择匹配项之前的行-使用输入字符串变量时Select-String -Context问题 [英] PowerShell: Select line preceding a match -- Select-String -Context issue when using input string variable

查看:236
本文介绍了PowerShell:选择匹配项之前的行-使用输入字符串变量时Select-String -Context问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在多行字符串变量上返回匹配项之前的一行.

I need return a line preceeding a match on a multi-line string variable.

似乎在将字符串变量用于输入Select-String时,会将整个字符串视为已匹配.因此,Context属性位于字符串的任一端外部",并且为null.

It seems when using a string variable for the input Select-String considers the entire string as having matched. As such the Context properties are "outside" either end of the string and are null.

考虑以下示例:

$teststring = @"
line1
line2
line3
line4
line5
"@

Write-Host "Line Count:" ($teststring | Measure-Object -Line).Lines #verify PowerShell does regard input as a multi-line string (it does)

Select-String -Pattern "line3" -InputObject $teststring -AllMatches -Context 1,0 | % {
$_.Matches.Value #this prints the exact match
$_.Context #output shows all context properties to be empty 
$_.Context.PreContext[0] #this would ideally output first line before the match
$_.Context.PreContext[0] -eq $null #but instead is null
}

我在这里误会了吗?

匹配"line3"时返回"line2"的最佳方法是什么?

What is the best way to return "line2" when matching for "line3"?

谢谢!

我忽略声明的其他要求: 需要在所有匹配的行上方提供不确定长度的字符串. EG在下面搜索"line3"时,我需要返回"line2"和"line5".

Additional requirements I neglected to state: Needs to provide the line above ALL matched lines for a string of indeterminate length. EG when searching the below for "line3" I need to return "line2" and "line5".

line1
line2
line3
line4
line5
line3
line6

推荐答案

Select-String 对输入的数组进行操作,因此而不是单行,多行字符串,您必须提供行数组 ,以使-Context-AllMatches能够按预期工作:

Select-String operates on arrays of input, so rather than a single, multiline string you must provide an array of lines for -Context and -AllMatches to work as intended:

$teststring = @"
line1
line2
line3
line4
line5
line3
line6
"@

$teststring -split '\r?\n' | Select-String -Pattern "line3" -AllMatches -Context 1,0 | % {
  "line before:  " + $_.Context.PreContext[0]
  "matched part: " + $_.Matches.Value  # Prints the what the pattern matched
}

这将产生:

line before:  line2
matched part: line3
line before:  line5
matched part: line3

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆