在文件中搜索字符串并将内容打印到文件中



我有一种情况,我需要从文件末尾搜索一个从末尾开始的特定字符串。在到达字符串时,我需要进行另一个验证步骤来检查另一个字符串。例如,我需要搜索字符串";你好"从文件末尾开始。当我第一次穿越";你好"从最后开始,我需要继续搜索另一个字符串";启动";其正好在"0"之上5行;你好"线

我试着在下面的代码片段中搜索";你好"一串我如何搜索";启动";字符串来自";你好"?

$Test   = "C:TempTest.txt"
$looking = "Hello"
$Morelooking = "Starting"
$Info = Get-Content -Path $Test
if(Get-Content -Path $Test)
{
if (($Info -like $looking).Count -eq 0) 
{
Write-Output "Not found"
}
else
{
$Output = @()
for($i = ($Info.Count -1); $i -ge 0; $i--) 
{
$Output += $Info[$i]
if ($Info[$i] -like $looking) 
{ 
break;
}
}
[array]::Reverse($Output)
}
}

如果您的文件看起来像这样:

blah blah blah 
blah blah
Starting something
blah blah blah blah 
blah blah blah blah blah 
blah blah blah blah 
blah 
Hello World
the end

您可以以相反的顺序循环浏览文件的行

$Test        = "C:TempTest.txt"
$looking     = "Hello"
$Morelooking = "Starting"
$Info        = Get-Content -Path $Test
# because we use the regex `-match` operator, escape the search terms
$looking     = [Regex]::Escape($looking)
$Morelooking = [Regex]::Escape($Morelooking)
# loop through the lines in reversed order
for ($i = $Info.Count -1; $i -ge 0; $i--) {
if ($Info[$i] -match $looking) {
Write-Host "'$looking' found in line $($i + 1)" -ForegroundColor Green  # humans count from line 1
if ($i -gt 4 -and $Info[$i - 5] -match $Morelooking) {
Write-Host "'$Morelooking' found in line $($i - 4)`r`n" -ForegroundColor Green
# print the lines from the array where the matches are found
($i - 5)..($Info.Count -1) | ForEach-Object { $Info[$_] }
}
else {
Write-Host "'$Morelooking' not found" -ForegroundColor Red
}
break
}
}

输出:

'Hello' found in line 8
'Starting' found in line 3
Starting something
blah blah blah blah 
blah blah blah blah blah 
blah blah blah blah 
blah 
Hello World
the end

要获得某个匹配项上方的5行,可以使用Select-String-Context参数:

# Let's start by escaping the search terms
$looking = [regex]::Escape($looking)
$Morelooknig = [regex]::Escape($Morelooking)
# Search for the "hello" string, ask for 5 lines of "pre-context"
enter code here
$matchesWithContext = Select-String -Path $Test -Pattern $looking -Context 5,0 -AllMatches
# Select that _last_ match:
$lastMatchWithContext = $matchesWithContext |Select -Last 1
# Test if the 5th line above (the first of our pre-context lines) contains "starting"
$lastMatchWithContext.Context.PreContext[0] -match $Morelooking

最新更新