首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提取特定文本和提取

提取特定文本和提取
EN

Stack Overflow用户
提问于 2021-03-31 18:37:38
回答 1查看 49关注 0票数 0

我正在尝试创建一个PowerShell来读取SQL Dump文本文件,并从特定的搜索点'CREATE TABLE fks_common.bo_bdsvragen‘读取该文件,直到我找到';)’为止。我想提取并写入一个新文件。我刚刚开始学习PowerShell,确实需要一些帮助。此外,由于搜索转储文件非常大(40 is ),因此解决方案执行起来也很好。

代码语言:javascript
复制
$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
}
EN

回答 1

Stack Overflow用户

发布于 2021-03-31 21:54:48

我认为您已经为表声明的末尾交换了字符;)应该为);

对于这样的大文件,使用switch是最快的。

假设您的dump.sql文件如下所示:

代码语言:javascript
复制
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

然后,您可以这样做来提取您感兴趣的文本,如下所示:

代码语言:javascript
复制
# 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'

输出:

代码语言:javascript
复制
CREATE TABLE fks_common.bo_bdsvragen (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255)
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66886161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档