1

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)

2
  • 1
    Try Select-String -path $infile -Pattern '^\s*(\S+) WANT THIS' -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value} Commented Sep 28, 2018 at 14:04
  • Your solution works a lot better than mine - if you paste it as an answer, I'll accept it. Commented Sep 28, 2018 at 14:58

2 Answers 2

2

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

  • ^ - start of a line
  • \s* - 0+ whitespaces
  • (\S+) - Group 1: one or more non-whitespace chars
  • WANT THIS - a literal substring.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't one Foreach-Object {$_.Matches.Groups[1].Value} suffice? (+1)
Strange, I just checked with PSv5.1 and PSv6.1 and both returned proper results with sls $infile -Pattern '^\s*(\S+).*want'|%{$_.Matches.Groups[1].Value}
0

Re-reading the code, its matching them all, but only writing the value of the first match (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!!!!

1 Comment

This regex won't match pqr WANT THIS line, since it starts with a whitespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.