Thomas Joseph
Thomas Joseph

Reputation: 67

Powershell search till a particular keyword

I'm trying to search and extract the sentences that start with a particular keyword, and which exist between/starts/ends with a keyword. The intention is to extract sentences starting with 'ALTER TABLE', which are either nested between 'GO' keyword or have GO on begin or end block of it. The number of sentences that exist between GO keyword could be arbitrary. Here is my sample file and the code that was written to achieve it.

Content of SampleFile.sql

ALTER TABLE [dbo].[test1]    
    ADD [country] VARCHAR (30) NULL;
GO
alter procedure 
    some procedure code
GO
ALTER TABLE 
    something;
GO
PROCEDURE ALTER TABLE;
Drop table;
GO
ALTER TABLE [dbo].[test2]    
    ADD [continent] VARCHAR (30) NULL;

My code

$path = 'D:\Script'
$sampleFile = 'SampleFile.sql'
$search = "ALTER TABLE"
(GC $path\$sampleFile -Delimiter 'GO') -match "^$search*"

Using this code, I'm able to fetch the content only of the first set of ALTER, until the GO. If the caret regex is avoided (^), then all instances of 'ALTER TABLE' is printed (which will also include the sentence 'PROCEDURE ALTER TABLE' until the next GO). Only the sentences starting with 'ALTER TABLE' is required.

Upvotes: 1

Views: 38

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626923

You just need the multiline modifier:

(GC $path\$sampleFile -Delimiter 'GO') -match "(?m)^$search*"
                                                ^^^

that will make ^ match the beginning of a line, not the whole string.

enter image description here

Upvotes: 2

Related Questions