匹配Powershell中两个单词之间的所有内容 [英] Match everything between two words in Powershell

查看:143
本文介绍了匹配Powershell中两个单词之间的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在EXEC SQL的两个段之间有一个带有SQL查询的大文本文件--- END-EXEC.

I have a big text file with SQL query in between blocks of EXEC SQL --- END-EXEC.

我需要介于EXEC SQL --- END-EXEC之间的所有内容.关键字.示例输入如下.

I need everything in-between EXEC SQL --- END-EXEC. keywords. Sample Input is below.

这就是我要尝试的方法.如果有一块EXEC SQL --- END-EXEC,我就能得到内容.但是,如果有多个EXEC SQL --- END-EXEC.块,我失败了.

This is how I'm trying to do. I'm able to get the contents if there is one block of EXEC SQL --- END-EXEC. However, If there are multiple EXEC SQL --- END-EXEC. blocks, I am failing.

a)以字符串形式读取文件.

a) Read the file as a string.

我要使用

$content = [io.file]::ReadAllText("$pathtofile")
$content = $content -replace "\s*`n", " " 

 (p.s. I'm using V2.0 so cannot use -raw option)

b)然后我执行此操作以匹配EXEC关键字之间的所有内容.

b) Then I doing this to match everything in between EXEC keyword.

$result = $content -match "EXEC(.*)EXEC"
$matches[0] > D:\result.txt

输入:

   * ABCD ABCD ABCD BLAH BLAH BLAH - This is some text preceding EXEC SQL

    **EXEC SQL** 
    DECLARE TMPMOTT-CUR CURSOR FOR 
          SELECT KONTYP                     
                ,BFDAT                       
                ,MARK 
                ,MOTT 
                ,AVS     
                ,BEL                      
                ,OKLBE                  
          FROM  ABCBEFGH                      
          ORDER BY MOTT                  

    **END-EXEC**.                               

    * ABCD ABCD ABCD BLAH BLAH BLAH  - This is some text after END-EXEC. 

推荐答案

$script = Get-Content D:\temp\script.sql

$in = $false

$script | %{
    if ($_.Contains("EXEC SQL"))
        { $in = $true }
    elseif ($_.Contains("END-EXEC"))
        { $in = $false; }
    elseif ($in)
        { Write-Host $_ } # Or Out-File ...
}

这篇关于匹配Powershell中两个单词之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆