Formatting output from Select-String -Context

This topic contains 5 replies, has 4 voices, and was last updated by  tmack8080 1 month ago.

  • Author
    Posts
  • #82168

    tmack8080
    Participant

    Hi Guys,

    I have a text file that looks like so:

    [Engine0]
    Host=Server01
    Port=11000

    [Engine1]
    Host=Server02
    Port=12000

    [Engine2]
    Host=Server03
    Port=13000

    I tried

    Select-String -Path file.txt -Pattern "Host=" -Context 1,1

    which gives me the desired output but a side effect of Select-String is the filename and line number is included in the output. How can I make my output appear the same as above using the -Context parameter? Stated differently, how can I make the output look exactly like the Select-String "Line" method?

    Thanks

  • #82171

    Naw Awn
    Participant

    is this what you are looking for?

    Get-Content -Path file.txt | Select-String -Pattern "Host=" -Context 1,1
    
      [Engine0]
    > Host=Server01
      Port=11000
      [Engine1]
    > Host=Server02
      Port=12000
      [Engine2]
    > Host=Server03
      Port=13000
    
    • #82177

      tmack8080
      Participant

      That works!

      Get-Content -Path file.txt | Select-String -Pattern "Host=" -Context 1,1 | Out-File tempHost.txt
      (Get-Content tempHost.txt).TrimStart(">")

      Anybody know a cleaner way to do that?

      Thanks for the solution Naw Awn.

  • #82174

    Olaf Soyk
    Participant

    I'm not completely sure if I got what exactly you want to get. If you're not sure what property of the result you want you can simply output all properties like this:

    Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object *

    If you then identified the propery you nee you can select only this like this:

    Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object -Property Line

    If you like to eliminate even the header you can do this:

    Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object -ExpandProperty Line
  • #82280

    Curtis Smith
    Participant

    The way I'm reading it, it sound like you're looking for something more like this.

    Select-String -Path "D:\New Text Document.txt" -Pattern "Host=" -Context 1,1 |
    ForEach-Object {
        $_.Context.PreContext
        $_.Line
        $_.Context.PostContext
    }
    • #82414

      tmack8080
      Participant

      Yeah this works too. Thanks!

You must be logged in to reply to this topic.