在powershell中列出并分类包含字符串X的所有文件的方法

Mit*_*tch 2 powershell

目前,当我在 powershell 中查找一堆文件中的字符串时,我使用以下命令:

PS: C:\> ls -r | Select-String "dummy" | ls -r
Run Code Online (Sandbox Code Playgroud)

这会列出所有包含该字符串的文件。如果我做任何一个

PS: C:\> ls -r | Select-String "dummy" | ls -r | cat
PS: C:\> ls -r | Select-String "dummy" | cat
Run Code Online (Sandbox Code Playgroud)

它将再次搜索并捕获包含该字符串的所有文件,但所有内容都以一个块的形式出现,例如

file 1 line 1
file 1 line 2
file 2 line 1
file 3 line 1
file 4 line 1
Run Code Online (Sandbox Code Playgroud)

但无法判断哪一行位于哪个文件中。有没有办法让它列出类似的内容:

File 1.txt:
file1 line1
file2 line2

File 2.txt:
file2 line1
Run Code Online (Sandbox Code Playgroud)

等。最好使用单衬,但不是必需的

Isz*_*szi 6

有人可能会说这不是一句单行话,但它在任何情况下都应该有效(“应该”意味着我还没有测试它,但脚本应该是正确的):

Get-ChildItem -Recurse | Where-Object {(Select-String -InputObject $_ -Pattern 'dummy' -Quiet) -eq $true} | ForEach-Object {Write-Output $_; Get-Content $_}
Run Code Online (Sandbox Code Playgroud)

扩展,带有评论:

# Get a listing of all files within this folder and its subfolders.
Get-ChildItem -Recurse |

# Filter files according to a script.
Where-Object {
    # Pick only the files that contain the string 'dummy'.
    # Note: The -Quiet parameter tells Select-String to only return a Boolean. This is preferred if you just need to use Select-String as part of a filter, and don't need the output.
    (Select-String -InputObject $_ -Pattern 'dummy' -Quiet) -eq $true
} |

# Run commands against each object found.
ForEach-Object {
    # Output the file properties.
    Write-Output $_;

    # Output the file's contents.
    Get-Content $_
}
Run Code Online (Sandbox Code Playgroud)

如果你真的想要简短的话,这里有一个“高尔夫”版本。这绝对更接近“一线”的资格。

ls -R|?{$_|Select-String 'dummy'}|%{$_;gc $_}
Run Code Online (Sandbox Code Playgroud)

除了明显使用别名、折叠空格和截断参数名称之外,您可能还需要注意“完整”版本和“高尔夫”版本之间的以下显着差异:

  • Select-String被交换为使用管道输入而不是-InputObject.
  • -Pattern中省略了参数名称,Select-String因为该参数名称的使用是可选的。
  • -Quiet选项已从 中删除Select-String。过滤器仍然可以工作,但是需要更长的时间,因为它将Select-String处理每个完整的文件,而不是在第一个匹配行之后停止。
  • -eq $true被从过滤规则中省略。当过滤器脚本已返回布尔值时,如果您只想让它在布尔值为 true 时工作,则无需添加比较运算符和对象。
    • (另请注意,这适用于某些非布尔值,例如在此脚本中。这里,匹配将生成一个填充的数组对象,该对象被视为 true,而不匹配将返回一个空数组,该数组被视为错误的。)
  • Write-Output被省略了。如果在没有命令的情况下给出对象,PowerShell 将尝试将此作为默认操作。

如果您不需要文件的所有属性,而只想将完整路径放在文件内容之前的一行上,则可以使用以下命令:

ls -R|?{$_|Select-String 'dummy'}|%{$_.FullName;gc $_}
Run Code Online (Sandbox Code Playgroud)