简体   繁体   English

上下文输出到 CSV 文件

[英]Context Output into CSV file

I need to search 10-15 strings into the entire application codes(more than 10000 programs) so I have inserted the strings that i need to search in a text file "strings.text".我需要在整个应用程序代码(超过 10000 个程序)中搜索 10-15 个字符串,所以我在文本文件“strings.text”中插入了我需要搜索的字符串。 I also need to know the previous and next line of the matched string line so I am using "Context 1" in the below script.我还需要知道匹配字符串行的上一行和下一行,所以我在下面的脚本中使用了“上下文 1”。 However, the below script is giving output as only Matched String line.但是,下面的脚本仅将输出作为匹配字符串行。

$content = Get-Content strings.txt
ForEach ($Word in $content){
  Get-ChildItem -recurse |
    Select-String -pattern $Word -Context 1 |
    Select-  path,line,linenumber,filename |
    Export-csv -Path "\result_$word.csv"
}

Output:输出:

Path                Line          LineNumber   FileName
desktop\prog1.txt   Server(xyz)   3            prog1.txt
desktop\prog2.txt   Server(xyz)   6            prog2.txt

What I really want is:我真正想要的是:

Path                Line          LineNumber   FileName
                    Connect       2            prog1.txt
desktop\prog1.txt   Server(xyz)   3            prog1.txt
                    stop          4            prog1.txt

                    Connect       8            prog2.txt
desktop\prog2.txt   Server(xyz)   9            prog2.txt
                    stop          10           prog2.txt

Can anyone please help how can I get this output?任何人都可以请帮助我如何获得此输出? Please suggest if there is any other way to get the required output.请建议是否有任何其他方法可以获得所需的输出。

If you want to export to a CSV you need to create separate objects for each CSV line.如果要导出为 CSV,则需要为每个 CSV 行创建单独的对象。 Try something like this:尝试这样的事情:

foreach ($Word in $content){
  Get-ChildItem -Recurse |
    Select-String -Pattern $Word -Context 1 |
    ForEach-Object {
      New-Object -Type PSCustomObject -Property @{
        Path       = ''
        Line       = $_.Context.PreContext[-1]
        LineNumber = $_.LineNumber - 1
        Filename   = $_.FileName
      }
      New-Object -Type PSCustomObject -Property @{
        Path       = $_.Path
        Line       = $_.Line
        LineNumber = $_.LineNumber
        Filename   = $_.FileName
      }
      New-Object -Type PSCustomObject -Property @{
        Path       = ''
        Line       = $_.Context.PostContext[0]
        LineNumber = $_.LineNumber + 1
        Filename   = $_.FileName
      }
    } | Export-Csv -Path "\result_$word.csv" -NoType
}

$_.Context.PreContext[-1] is the last line of the pre-context, $_.Context.PostContext[0] is the first line of the post-context. $_.Context.PreContext[-1]是前上下文的最后一行, $_.Context.PostContext[0]是后上下文的第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM