gpt4 book ai didi

powershell - Powershell Select-String:如何获取完整的路径和上下文行

转载 作者:行者123 更新时间:2023-12-02 23:11:59 25 4
gpt4 key购买 nike

我有这个工作

select-string -path C:\test\*.txt -pattern "test" -allmatches –simplematch | foreach-object {
Write-Host $_.Filename
Write-Host $_.LineNumber
Write-Host $_.Line
Write-Host $_.context.postcontext
}

但是我也想获得FullPath而不只是FileName。我也想在Line之前和之后获得上下文行,但似乎无法使其正常工作。

最佳答案

该文件路径在Path -property中可用。要获得上下文,您需要首先指定在使用-Context 2(前后2行)或-Context 1,2(之前1行,之后2行)之前和之后捕获多少行。例如

select-string -path C:\test\*.txt -pattern "test" -AllMatches -SimpleMatch -Context 1,1 | foreach-object {
Write-Host
Write-Host "MATCH!"
Write-Host "-------------"
Write-Host "Path $($_.Path)"
Write-Host "Line number: $($_.LineNumber)"
Write-Host "Before: $($_.Context.Precontext)"
Write-Host "Line: $($_.Line)"
Write-Host "After: $($_.Context.Postcontext)"
}

输入样例(Text1.txt):
Line 1
Line 2
Line test
Line 4
Line 5

样本输出:
MATCH!
-------------
Path C:\test\Text2.txt
Line number: 4
Before: Line 3
Line: Line test
After: Line 5

MATCH!
-------------
Path C:\test\Text1.txt
Line number: 3
Before: Line 2
Line: Line test
After: Line 4

关于powershell - Powershell Select-String:如何获取完整的路径和上下文行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com