1
$input_path = "d:\txt\*.txt"
$output_file = 'd:\out.txt'
$regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

Powershell beginner here. I'd like it to loop through all files in a specific directory, search for a specific regex pattern and output the results to a file. So far I've managed to work out the above. How can I have it also output the filename for each match?

2 Answers 2

1

You can do the following:

$input_path = "d:\txt\*.txt"
$output_file = 'd:\out.txt'
$regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
Select-String -Path $input_path -Pattern $regex -AllMatches | Foreach-Object {
    $currentMatches = $_
    $_.Matches | Foreach-Object { $_.Value,$currentMatches.Filename -join ' | ' } |
        Add-Content $output_file
}

Explanation:

Select-String will return a collection of MatchInfo objects. Each of those objects has a Filename property that contains only the filename of the file containing the match(es). Since there could be multiple matches (due to -AllMatches) in a single file, it is necessary to iterate through each match within a MatchInfo object.

The -join operator joins all items in a collection with a defined string delimiter.

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

Comments

1

So for your last line, use:

# put matches into var
$matches = Select-String -Path $input_path -Pattern $regex -AllMatches
# write out to file
foreach ($m in $matches) { $m.Filename | Out-File $output_file -Append -NoClobber }

3 Comments

Thank you RobotScience! I'll avoid aliases for now. Using your line I somehow still don't get the filename though. Not sure what I'm doing wrong here.
Ah you wanted the filename, I updated my answer. Hopefully that works better for you.
Yes I was trying to get something like Stphn Lastname was born in 1995 xyz | 1.txt Robot Science was born in 1996 xyz | 2.txt

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.