output filename, not string with select-string

前端 未结 3 1160
栀梦
栀梦 2021-02-01 05:04

I\'m using powershell to \"grep\" my source code for a particular string. If the string is in the file, I would like the name of the file, not the line of code that contains th

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 05:17

    I don't think I completely understand what you're trying to do. If you want the output grouped by file, you can pipe into Format-Table with the -GroupBy parameter:

    gci . -include "*.sql" -recurse `
        | select-string -pattern 'someInterestingString' `
        | Format-Table -GroupBy Path
    

    If you want to get only the names of the files that match without any other info, you can use Select-Object with the -Unique parameter:

    gci . -include "*.sql" -recurse `
        | select-string -pattern 'someInterestingString' `
        | Select-Object -Unique Path
    

    If you're interested in only the file name, regardless whether the name itself appears multiple times in your hierarchy, then you can select the Filename property instead.


    Note: The Get-Member cmdlet is a great help in figuring out what properties exist on an object:

    gci . -include "*.sql" -recurse `
        | select-string -pattern 'someInterestingString' `
        | Get-Member
    

    You can also use its alias gm instead.

提交回复
热议问题