Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching newlines in regular expression with powershell

I have some data that looks like this:

:setvar DatabaseName "CI_1814903104"
:setvar DefaultFilePrefix "CI_1814903104"
--etc.    

GO

I wish to replace all sql cmd variable lines (lines that start with :setvar) with an empty string such that the data looks like this:

--etc.    

GO

This statement (where $script contains the data) seems to do the trick but still leaves the newlines:

$script -replace ":setvar(.*$)", ""

results in:

 
 
--etc.    

GO

How do I include the newline in the match? It seems to match it but not actually be replaced. Any help appreciated.

like image 834
Plymouth223 Avatar asked Sep 13 '13 03:09

Plymouth223


Video Answer


1 Answers

This assumes that your data is being read in from some file. Depending on how you are reading in your data, you may have a collection of strings instead of a single string.

PS C:\> $script = Get-Content data.txt

# Get-Content returns each line as a string object in an Object[].
PS C:\> $script.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS C:\> $script[0].GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Piping Get-Content to Out-String as demonstrated below will ensure that you get a single string, and then you can operate on the windows newline character to remove the appropriate lines.

PS <C:\> $script = ( Get-Content data.txt | Out-String ).Trim()
PS <C:\> $script -replace ":setvar(.*)`n", ""
--etc.

GO
like image 168
Anthony Neace Avatar answered Sep 21 '22 20:09

Anthony Neace