Search code examples
powershelltext

PowerShell script that searches for a string in a .txt and if it finds it, looks for the next line containing another string and does a job with it


I have the line

Select-String -Path ".\*.txt" -Pattern "6,16" -Context 20 | Select-Object -First 1

that would return 20 lines of context looking for a pattern of "6,16".

I need to look for the next line containing the string "ID number:" after the line of "6,16", read what is the text right next to "ID number:", find if this exact text exists in another "export.txt" file located in the same folder (so in ".\export.txt"), and see if it contains "6,16" on the same line as the one containing the text in question.

I know it may seem confusing, but what I mean is for example:

example.txt:5218: ID number:0002743284

shows whether this is true:

export.txt:9783: 0002743284 *some text on the same line for example* 6,16


Solution

  • If I understand the question correctly, you're looking for something like:

    Select-String -List -Path *.txt -Pattern '\b6,16\b' -Context 0, 20 |
      ForEach-Object {
        if ($_.Context.PostContext -join "`n" -match '\bID number:(\d+)') {
          Select-String -List -LiteralPath export.txt -Pattern "$($Matches[1]).+$($_.Pattern)"
        }
      }
    
    • Select-String's -List switch limits the matching to one match per input file; -Context 0,20 also includes the 20 lines following the matching one in the output (but none (0) before).

      • Note that I've placed \b, a word-boundary assertion at either end of the search pattern, 6,16, to rule out accidental false positives such as 96,169.
    • $_.Context.PostContext contains the array of lines following the matching line (which itself is stored in $_.Line):

      • -join "`n" joins them into a multi-line string, so as to ensure that the subsequent -match operation reports the captured results in the automatic $Matches variable, notably reporting the ID number of interest in $Matches[1], the text captured by the first (and only) capture group ((\d+)).
    • The captured ID is then used in combination with the original search pattern to form a regex that looks for both on the same line, and is passed to a second Select-String call that searches through export.txt

      • Note: An object representing the matching line, if any, is output by default; to return just $true or $false, replace -List with -Quiet.