Help searching through text file

This topic contains 7 replies, has 3 voices, and was last updated by  John Boyd 4 months, 2 weeks ago.

  • Author
    Posts
  • #88609

    James M borne
    Participant

    Good Morning kind nerds, I am struggling with something i'm sure is very easy to someone out there.

    Essentially I want to search through a text log file for a string, if I find that string then I want to take the line BELOW the one I found and add it to a new array.

    Then from that array I want to take the last 2 characters (which will be a number) in each element and total them up.

    I have got this far (pathetic i know but in my defence I am not a coder for many many years)

    $text= Get-Content -Path "C:\Users\me\test\log.txt"

    $text| Where-Object {$_ -like '*String I want to find*'}

    So I have done the first bit, finding the string I want – but that's as far as I managed to get.

  • #88619

    John Boyd
    Participant

    I would do something like this

    $Pattern =@("String I want to find", "somthing else maybe")
    $test= get-content file.txt|Select-String -Pattern $pattern -SimpleMatch
    $test

    • #88622

      James M borne
      Participant

      Thank you John, that seems to achieve the first part as I have already done. Any ideas how I create the array of "next" lines?

    • #88631

      Olaf Soyk
      Participant

      You could use the cmdlet Select-String and use the parameter -Context to capture the surrounding lines around a match.

  • #88639

    James M borne
    Participant

    Thanks guys, I have now managed to get the line and the next line (which was the one that I wanted) into an array. Now to strip the lines I dont want 🙂

  • #88642

    John Boyd
    Participant

    this works sort of not sure what you want as a return if there is nothing found after that line or if the line after is null.
    Also $test has everything in it and acts as an array. If you need to manipulate the data in each line further you would need some logic to split the lines. Hopefully the below gives you some help

    $Pattern =@("String I want to find", "somthing else maybe")
    $test= get-content file.txt|Select-String -Pattern $pattern -SimpleMatch -Context 0, 1 | % {$_.Context.PostContext}
    $test |% { $testarray = $_ -split '#'
    Write-Host $testarray[0]
    Write-Host $testarray[1]
    }

    • #88643

      James M borne
      Participant

      Just wanted to thank all of you especially John, I have managed to get what I needed (with a little excel help afterwards)

  • #88726

    John Boyd
    Participant

    Glad I could help I just joined today and this was the first post I read.

You must be logged in to reply to this topic.