Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select-string how to only return first match line in first file

I am searching a directory for pattern, switches are -SimpleMatch -List. But it returns a list of files. How to do it to return only first file and first line in it?

like image 935
Sheen Avatar asked Aug 19 '14 11:08

Sheen


People also ask

How do I select a specific string in PowerShell?

You can type `Select-String` or its alias, `sls`. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

How do you select the first line in PowerShell?

If we want to only get the first line of a file we can use the Get-Content cmdlet and pipe this to the Select-Object cmdlet and use the First parameter to retrieve one line.

Is Select-String case sensitive?

Select-String uses the Pattern parameter to specify HELLO. The CaseSensitive parameter specifies that the case must match only the upper-case pattern. SimpleMatch is an optional parameter and specifies that the string in the pattern isn't interpreted as a regular expression.


1 Answers

Just use the Select-Object command to return the first match. You don't need to use Get-ChildItem since you can specify the path parameter in Select-String. The Select-String command returns MatchInfo object which contains the matching line and also the name of the file.

$m = Select-String -Pattern get -Path *.ps1 -list -SimpleMatch | select-object -First 1
$m.Line
$m.Path
like image 194
bouvierr Avatar answered Oct 04 '22 07:10

bouvierr