我正在尝试创建一个PowerShell来读取SQL Dump文本文件,并从特定的搜索点'CREATE TABLE fks_common.bo_bdsvragen‘读取该文件,直到我找到';)’为止。我想提取并写入一个新文件。我刚刚开始学习PowerShell,确实需要一些帮助。此外,由于搜索转储文件非常大(40 is ),因此解决方案执行起来也很好。
$Zoektext = '*CREATE TABLE fks_common.bo_bdsvragen*'
$FILE = Get-Content "c:\scripts\dump.sql" | Where-object {$_ -like $Zoektext}
foreach ($LINE in $FILE)
{
$Tekst = 'Op regel ' + $Line.ReadCount + ' staat ' + $LINE
Write-Output $Tekst
}发布于 2021-03-31 21:54:48
我认为您已经为表声明的末尾交换了字符;)应该为);
对于这样的大文件,使用switch是最快的。
假设您的dump.sql文件如下所示:
blah
blahblahblah
blahblahblahblah
CREATE TABLE fks_common.bo_bdsvragen (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
more blah
and a lot more blahblah然后,您可以这样做来提取您感兴趣的文本,如下所示:
# create two regex escaped strings for the beginning and end of the table declaration
$tableBegin = [regex]::Escape('CREATE TABLE fks_common.bo_bdsvragen')
$tableEnd = [regex]::Escape(');')
# set a boolean flag to $false
$foundBegin = $false
# loop through the text line-by-line and capture only what you seek
$result = switch -Regex -File 'c:\scripts\dump.sql' {
$tableBegin { $foundBegin = $true; $_ } # set the flag and output this line
$tableEnd { if ($foundBegin) { $_ ; break } } # we've reached the end of the CREATE_TABLE declaration
default { if ($foundBegin) {$_ } } # only output this line if $foundBegin is $true
}
# output on screen
$result
# output to new file
$result | Set-Content -Path 'c:\scripts\table.sql'输出:
CREATE TABLE fks_common.bo_bdsvragen (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);https://stackoverflow.com/questions/66886161
复制相似问题