我有一個日志檔案,里面有幾萬行,我需要關鍵字 A 和 B 之間的這些內容。關鍵字 A 和 B 在檔案中是唯一的。如何通過 Power Shell 腳本獲取內容并將內容保存到新檔案?任何建議表示贊賞。謝謝。
輸入資料可能如下所示:
A
sprd-spipe: spipe 5-4 not ready to open!
sprd-spipe: spipe 5-4 not ready to open!
systemserver cmd , get para: ( 50)
sprd-spipe: spipe 5-4 not ready to open!
sprd-spipe: spipe 5-6 not ready to open!
sprd-spipe: spipe 5-4 not ready to open!
B
我試過的
cls
$text = gc -raw D:\test\example_out.txt
Write-Host $text
$regex = '(?ms)A:(. ?)B:'
#Output
[regex]::Matches($text,$regex) |
foreach {$_.groups[1].value } |
Out-File D:\test\example_outs.txt -Encoding utf8
$result = gc -raw D:\test\example_outs.txt
Write-Host $result
和
$test1 = 'A'
$text2 = 'B'
Get-Content D:\test\example_out.txt | Select-String - From $test1 - To $test2 | Set-Content D:\test\outfile.txt
但不能得到正確的結果。
更新1
使用(?ms)A\n(. ?)B\n?,它的作業原理。
日志中的A和B應該是一個句子,現在,我把腳本改成
$text = gc -raw D:\test\dumpstate-2021-12-08-21-22-53.txt
$A= 'DUMP OF SERVICE batterystats:'
$B = 'Per-PID Stats:'
#Write-Host $text
$regex = '(?ms)$A\n(. ?)$B\n?'
#Output
[regex]::Matches($text,$regex) |
foreach {$_.groups[1].value } |
Out-File D:\test\example_outs.txt -Encoding utf8
$result = gc -raw D:\test\example_outs.txt
Write-Host $result
它沒有回傳結果
DUMP OF SERVICE batterystats:
sprd-spipe: spipe 5-4 not ready to open!
sprd-spipe: spipe 5-4 not ready to open!
systemserver cmd , get para: ( 50)
sprd-spipe: spipe 5-4 not ready to open!
sprd-spipe: spipe 5-6 not ready to open!
sprd-spipe: spipe 5-4 not ready to open!
Per-PID Stats:
uj5u.com熱心網友回復:
根據您更新的問題,大多數情況下一切都很好。
這就是 siad,如果要在字串中擴展變數,則需要使用雙引號字串而不是單引號字串。
因此,這里的正則運算式陳述句:
$A= 'DUMP OF SERVICE batterystats:'
$B = 'Per-PID Stats:'
#Write-Host $text
$regex = '(?ms)$A\n(. ?)$B\n?'
需要改為:
"(?ms)$A\n(. ?)$B\n?"
筆記:
你應該看看一些 .net regex 測驗在線工具。它們非常實用,可以微調您的正則運算式陳述句,直到得到您想要的結果。這不會解決您的參考問題(單引號與雙引號問題),但會幫助您找到正確的正則運算式陳述句并在您進行實驗時實時查看結果。
參考:
關于報價規則
單引號字串
用單引號括起來的字串是逐字字串。字串將完全按照您鍵入的方式傳遞給命令。不執行替換
雙引號字串
用雙引號括起來的字串是可擴展的字串。在將字串傳遞給命令進行處理之前,以美元符號 ($) 開頭的變數名稱將替換為變數的值。
在線正則運算式測驗器 ( https://regexstorm.net/tester )
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380578.html
標籤:电源外壳
