如何使用开始和结束字符串或字符过滤文本

时间:2016-02-07 14:58:01

标签: powershell

任何人都可以协助我过滤横幅信息并仅提取文本“13:12:03.539 UTC 2015年3月6日”作为输出吗?

C
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
S Y S T E M   A C C E S S   W A R N I N G
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
You have connected to a private network.  This system is to only be used
by authorized personnel for authorized business purposes.  All activity
is monitored and logged.  Unauthorized access or activity is a violation
of law.
If you have connected to this system by mistake, disconnect now.

13:12:03.539 UTC Sun Mar 6 2015
C
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
S Y S T E M   A C C E S S   W A R N I N G
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
You have connected to a private network.  This system is to only be used
by authorized personnel for authorized business purposes.  All activity
is monitored and logged.  Unauthorized access or activity is a violation
of law.
If you have connected to this system by mistake, disconnect now.

    Line       User       Host(s)              Idle       Location
*514 vty 0     vijay.dada idle                 00:00:01 X.X.X.X
  Interface    User               Mode         Idle     Peer Address
C
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
   S Y S T E M   A C C E S S   W A R N I N G
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
You have connected to a private network.  This system is to only be used
by authorized personnel for authorized business purposes.  All activity
is monitored and logged.  Unauthorized access or activity is a violation
of law.
If you have connected to this system by mistake, disconnect now.

我尝试使用以下代码无法使其正常工作。请求协助。

$arr = @()
$path = "yourFilePath"
$pattern = "(?<=.*C
-)\w+?(?=disconnect now.*)"

Get-Content $path | Foreach {
    if ([Regex]::IsMatch($_, $pattern)) {
        $arr += [Regex]::Match($_, $pattern)
    }
}
$arr | Foreach {$_.Value}

1 个答案:

答案 0 :(得分:4)

只需点击您正在寻找的行:

$path    = 'C:\path\to\your.txt'
$pattern = '^\d{2}:\d{2}:\d{2}\.\d{3} .* \w{3} \d{1,2} \d{4}$'

(Get-Content $path) -match $pattern

要删除您不想要的内容而不是选择您想要的内容,您需要将文本转换为单个字符串(默认情况下Get-Content会产生一系列字符串和多行匹配不会使用那种输入)然后替换该字符串中的横幅,例如像这样:

$path   = 'C:\path\to\your.txt'
$banner = @'
C
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
S Y S T E M   A C C E S S   W A R N I N G
-=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=- -=*=-
You have connected to a private network.  This system is to only be used
by authorized personnel for authorized business purposes.  All activity
is monitored and logged.  Unauthorized access or activity is a violation
of law.
If you have connected to this system by mistake, disconnect now.
'@ -replace "`r?`n", "`r`n"

((Get-Content $path | Out-String) -replace [regex]::Escape($banner)).Trim()

横幅定义中的尾随替换是确保横幅字符串具有编码为CR-LF的换行符,无论您是从脚本运行代码还是在PowerShell控制台中复制/粘贴代码。