Marc
Marc

Reputation: 9

Find the start and end of a string and write into CSV in Powershell

I have huge txt file with multiple lines in it.

I want to create an array which stores the start of a line with "PROCEDURE" and ends with "END;".

Then i need to search within the array [Start with "PROCEDURE" & Ends with "END;"] whether I have any lines with "EXCEPTION" as string.

If i don't find the string "EXCEPTION" within the array I have to write a message to a file the "Exception is not found", if found then write message as "Exception is found"

File Format for reference

-------------------------------------------------------------------
CLEAR;
EXIT

PROCEDURE FP_XXXXXX

IS

---------
---------
EXCEPTION

---------
---------
ENDS;

FUNCTION FF_

AS

--------
--------

Regards, Marc

Upvotes: 0

Views: 203

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

Let's break the problem down into:

  1. Read the lines from the file on disk
  2. Go through them until PROCEDURE is found
  3. For each subsequent line:
    • If line starts with END, return/quit
    • If not, check if it contains the string we're looking for

Translated to PowerShell, we might come up with something like this:

$started = $false
$exceptionFound = $false

# 1. Read the lines from the file
foreach($line in Get-Content .\path\to\file) {
  if(-not $started){
    # look for `PROCEDURE`
    $started = $line -clike 'PROCEDURE*'
    continue
  }

  # look for END
  if($line -clike 'END;*'){
    # we're done here
    break
  }

  # otherwise, look for the string
  $exceptionFound = $line -like '*exception*'
  if($exceptionFound){
    break
  }
}

# $exceptionFound will hold the answer at this point

Upvotes: 1

Related Questions