Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return only the matching regular expression when I select-string(grep) in PowerShell?

I am trying to find a pattern in files. When I get a match using Select-String I do not want the entire line, I just want the part that matched.

Is there a parameter I can use to do this?

For example:

If I did

select-string .-.-. 

and the file contained a line with:

abc 1-2-3 abc 

I'd like to get a result of just 1-2-3 instead of the entire line getting returned.

I would like to know the Powershell equivalent of a grep -o

like image 925
Skyler Avatar asked Apr 29 '09 23:04

Skyler


People also ask

How do I select a specific string in PowerShell?

Use Select-String in a function: PS C:\> function search-help { $pshelp = "$pshome\es\about_*. txt", "$pshome\en-US\*dll-help. xml" Select-String -path $pshelp -Pattern $args[0] } This simple function uses the Select-String cmdlet to search the Windows PowerShell Help files for a particular string.

Does select-string use regex?

The Select-String cmdlet uses regular expression matching to search for text patterns in input strings and files. You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text.

Is there a grep command in PowerShell?

Select-String (our PowerShell grep) works on lines of text and by default will looks for the first match in each line and then displays the file name, line number, and the text within the matched line.


1 Answers

Or just:

Select-String .-.-. .\test.txt -All | Select Matches 
like image 117
Keith Hill Avatar answered Oct 14 '22 04:10

Keith Hill