2016-02-07 75 views
1

任何人都可以幫助我篩選標題消息並僅提取文本「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. 

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} 

回答

4

只需用grep你要找的線路:

$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控制檯。

+0

絕對太棒了:)。短而甜。感謝很多,它工作。 – Vijay

+0

但它可以更廣泛地在其認爲橫幅模式的地方.Becoz我一直在運行不同的命令和每次輸出是不同的,但橫幅是相同的。 – Vijay

+0

@Vijay查看更新後的答案。 –

相關問題