Skip to content

Add a switch to Select-String that returns the matching parts only, analogous to grep -o #7712

@mklement0

Description

@mklement0

Related: #7713 and #7867

Sometimes all you want Select-String to do is to output only the matching parts of the input lines as strings, similar to what grep -o does on Unix-like platforms; e.g.:

# Extract only the parts that match the regex, each on its own line.
PSonUnix> "line1`nline2`nline3" | grep -o '[0-9]'
1
2
3

The equivalent Select-String solution is currently cumbersome:

PS> "line1", "line2", "line3" | Select-String '[0-9]' | ForEach-Object { $_.Matches[0].Value }
1
2
3

If we introduced a switch named, say, -MatchingPartOnly (name TBD, could have an alias of -o)
-OnlyMatching (see decision below), the command could be simplified to:

PS> "line1", "line2", "line3" | Select-String '[0-9]' -OnlyMatching

As an alias, -om could be considered (just -o could break existing code that used it for -OutVariable).

This would also speed up processing, because constructing [Microsoft.PowerShell.Commands.MatchInfo] instances can be bypassed.

Environment data

Written as of:

PowerShell Core 6.1.0-preview.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Committee-ReviewedPS-Committee has reviewed this and made a decisionFirst-Time-IssueEasy issues first time contributors can work on to learn about this projectHacktoberfestPotential candidate to participate in HacktoberfestIssue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Cmdlets-Utilitycmdlets in the Microsoft.PowerShell.Utility module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions