如何使用PowerShell在文件中找到的特定字符串之后搜索特定字符串

wr98u20j  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(283)

在使用PowerShell搜索了另一个名为Base的特定模式后,我试图在不同的行中找到一组特定的字符串,如Test2Test3Test4。为了同时生成Base、Test2、Test3和Test4行内容的报告,我编写了如下代码:然而,它并不总是得到所需的输出。文件数据如下所示

Base: some text
some line here
some line here
Test2: another text 
Test3: other text
Test4: different text
some lines here
some lines here
some lines here
Base: some text
some line here
some line here
Test2: another text 
Test3: other text
Test4: different text
some lines here
some lines here
some lines here
some lines here
.............
.............
$data = Get-Content $file
$req_data = $data |where {$_.Contains("Base") -or $_.Contains("Test2") -or $_.Contains("Test3") -or $_.Contains("Test4")}
$bases_data = $data |where {$_.Contains("Base")}
foreach ($basedata in $bases_data)
{
   $find_alias = ($req_data |select-string "^${basedata}$" -context (0.10)).Context.PostContext
   $final_data = "" | select Base, Test2, Test3, Test4
   $temp.Base = $basedata
   $temp.Test2 = ($find_alias |select-string "Test2").Tostring()
   $temp.Test3 = ($find_alias |select-string "Test3").Tostring()
   $temp.Test4 = ($find_alias |select-string "Test4").Tostring()
   $temp
}

预期产出应为:

Base                Test2                Test3              Test4
Base line data     Test2 line data      Test3 line data     Test4 line data
......             .........            .......             ....
gojuced7

gojuced71#

假设数据在文件中。您可以使用Select-String为任何字符串挑选相应的行。

$test_file = Get-Content C:\Informatica_POC\Test_file.txt

$test_file| Select-Object @{name='Base'; Expression={$_ |Select-string 'Base'} },
                          @{name='Test2'; Expression={$_ |Select-string 'Test2'} },
                          @{name='Test3'; Expression={$_ |Select-string 'Test3'} },
                          @{name='Test4'; Expression={$_ |Select-string 'Test4'} }|
                          Format-Table -AutoSize

我没有在格式上做太多的工作。但这也是可行的。希望能有所帮助。

相关问题