高效提取包含路径和行号的匹配行?

Efficiently extract matching lines including path and line number?

以下代码片段仅提取匹配的行,我还需要路径和行号:

Get-ChildItem $thePath\ -Include "*.txt" -Recurse | Get-Content | Select-String  -Pattern 'THE_PATTEN' | Set-Content "output.txt"

我试过这个方法,但它仍然只提取匹配的行:

Get-ChildItem $thePath\ -Include "*.txt" -Recurse | Get-Content | Select-String  -Pattern 'THE_PATTEN' | Select-Object -ExpandProperty Line | Set-Content "output.txt"

如何提取 路径:文件名:行号: 匹配行?

是的,您可以从 Select-String:

的输出中获取行号和文件名
ls *.txt | % { Select-String -Path $_ -Pattern "THE_PATTERN" | select-object LineNumber, Line, Path }

您会发现这种方法也快了一点。

祝你好运!

首先请注意 Get-ChildItem -FilterGet-ChildItem -Include 更有效(参见 help get-childitem)。接下来是 Select-String 接受文件。无需先获取内容。现在只需 Select 您需要的属性并导出您的文件。 (请注意,变量 $match$matches 是系统变量,因此您可能不想使用它们。)

$Patterns = Get-ChildItem $thePath -Filter "*.txt" -Recurse| Select-String  -Pattern 'THE_PATTEN' | select Path,Filename,LineNumber,Line

# Export to csv (usable in excel)
$Patterns | Export-Csv output.csv -NoTypeInformation # -Delimiter ";" #  the delimiter is optinal and depending of your region

# Exporting txt
foreach ($Pattern in $Patterns){
    ('{0} : {1} : {2}' -f ($Pattern.Path),($Pattern.LineNumber),($Pattern.Line)) | Add-Content "output.txt"
}

您不需要获取内容。路径通过管道。 (. 代表 -path,*.txt 代表 -filter 代表速度)

get-childitem -recurse . *.txt | select-string hi

foo2\file3.txt:1:hi
file1.txt:1:hi
file2.txt:1:hi