2016-09-23 78 views
0

首先,问一个非常简单的问题,因为我是全新的PowerShell的同学。如果搜索字符串匹配,只能读取PowerShell中的特定字词

我有文件,如:

"your>desired>output" START: this is th 
e output 
next line 
next line 
"your>desired>output" START: this is th 
e output 

如果“期望”这个词被发现,不是只读“产出”比 “这是输出”

如果我使用

我的任务是
Select-String *.txt -pattern "desired" 

大于输出是

"your>desired>output" START: this is th 

“电子输出”丢失。

任何形式的帮助表示赞赏。谢谢。

+1

'选择字符串* .TXT “期望” -Context 1 |%{$ _线。 $ _。Context.PostContext}' –

+0

@ MathiasR.Jessen检查一个关于上下文的欺骗,但你也可以做出答案(当然有一点解释) – Matt

+0

@ MathiasR.Jessen谢谢你的回应,但这并没有返回任何东西...... :(显示为错误,我在“期望”之前使用了额外的模式 – user6633897

回答

2

如果您希望x行匹配前后,可以使用-Context参数。

简要地标明你之前和比赛结束后要多少行,像这样:

Select-String $path $pattern -Context 1 

这将使我们前1线和每场比赛后,1号线。您可以通过所产生的MatchInfo对象的Context属性来访问这些行:

Select-String *.txt "desired" -Context 1 |ForEach-Object { 
    # Output the matched line 
    $_.Line 
    # And then the next line 
    $_.Context.PostContext 
} 
+0

再次感谢,但它没有给出正确的结果...... :( – user6633897