【问题标题】:Extract specific text and extract提取特定文本并提取
【发布时间】:2021-03-31 10:37:37
【问题描述】:

我正在尝试创建一个 PowerShell 来读取 SQL 转储文本文件并从特定搜索点“CREATE TABLE fks_common.bo_bdsvragen”读取此文件,直到我找到第一个位置“;)”。我想提取并写入新文件之间的行。我刚开始学习 PowerShell,肯定需要一些帮助。由于搜索转储文件非常大(40Gb),因此该解决方案的执行效果也很好。

$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
}

【问题讨论】:

标签: powershell


【解决方案1】:

我认为你已经交换了表声明结尾的字符 ;) 应该是 );

对于这样的大文件,使用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)
);

【讨论】:

  • 您好 Theo,感谢您提供此示例以及 switch 是多么强大的实用程序。它几乎可以解决问题。问题是它什么时候会发现迹象);首先它不起作用并停止并显示);也是结果。当您在文件中查找 2e of 3e... create table 时,就会出现这种情况。这可以解决,然后你让我开心。
  • @Ron 啊,是的。现在已经修好了。
  • 非常感谢。这对我帮助很大。
猜你喜欢
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多