Help searching through text file

Welcome Forums General PowerShell Q&A Help searching through text file

This topic contains 7 replies, has 3 voices, and was last updated by

 
Participant
1 year ago.

  • Author
    Posts
  • #88609

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

      Participant
      Points: 0
      Rank: Member

      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

      Participant
      Points: 263
      Helping Hand
      Rank: Contributor

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

  • #88639

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

      Participant
      Points: 0
      Rank: Member

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

  • #88726

    Participant
    Points: 0
    Rank: Member

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

The topic ‘Help searching through text file’ is closed to new replies.