[英]Select-string apply to multiple lines of input
I have a file like: 我有一个类似的文件:
abc WANT THIS
def NOT THIS
ghijk WANT THIS
lmno DO NOT LIKE
pqr WANT THIS
...
From which I want to extract: 我要从中提取:
abc
ghijk
pqr
When I apply the following: 当我应用以下内容时:
(Select-String -Path $infile -Pattern "([^ ]+) WANT THIS").Matches.Groups[1].Value >$outfile
It only returns the match for the first line: 它仅返回第一行的匹配项:
abc
(adding -AllMatches did not change the behaviour) (添加-AllMatches不会更改行为)
You may use 您可以使用
Select-String -path $infile -Pattern '^\s*(\S+) WANT THIS' -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value} > $outfile
The ^\\s*(\\S+) WANT THIS
pattern will match ^\\s*(\\S+) WANT THIS
模式将匹配
^
- start of a line ^
-一行的开始 \\s*
- 0+ whitespaces \\s*
-0+空格 (\\S+)
- Group 1: one or more non-whitespace chars (\\S+)
-第1组:一个或多个非空白字符 WANT THIS
- a literal substring. WANT THIS
-文字字符串。 Now, -AllMatches
will collect all matches, then, you need to iterate over all matches with Foreach-Object {$_.Matches}
and access Group 1 values (with Foreach-Object {$_.Groups[1].Value}
), and then save the results to the output file. 现在,
-AllMatches
将收集所有匹配项,然后,您需要使用Foreach-Object {$_.Matches}
-AllMatches
Foreach-Object {$_.Matches}
遍历所有匹配项并访问组1值(使用Foreach-Object {$_.Groups[1].Value}
) ,然后将结果保存到输出文件。
Re-reading the code, its matching them all, but only writing the value of the first match (doh!): 重新读取代码,将其全部匹配,但仅写入第一个匹配的值(doh!):
(Select-String -Path $scriptfile -Pattern "([^ ]+) WANT THIS").Matches.Groups.Value >$tmpfile
OTOH, it appears that the "captures" in the pattern output object also contain the "non-captured" content!!!! OTOH,似乎模式输出对象中的“捕获” 还包含“未捕获”内容!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.