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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With