7

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.

4

1 回答 1

13

这假设您的数据是从某个文件中读取的。根据您读取数据的方式,您可能有一个字符串集合而不是单个字符串。

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

如下所示将 Get-Content 连接到 Out-String 将确保您获得单个字符串,然后您可以对 windows 换行符进行操作以删除相应的行。

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

GO
于 2013-09-13T03:43:18.957 回答