我不知道如何从日志文件中提取所有内容(多行)。这是我需要从中提取的示例:
FieldCoilConnectivity=00
ConfigError=readback radio section
NfcErrorCode=0
[compare Errors]
我只需要提取这部分:
readback radio section
NfcErrorCode=0
我在此脚本中使用了powershell:
$input_path = ‘C:\Users\martin.kuracka\Desktop\temp\Analyza_chyb_SUEZ_CommTEst\022020\*_E.log’
$output_file = ‘C:\Users\martin.kuracka\Desktop\temp\Analyza_chyb_SUEZ_CommTEst\032020\extracted.txt’
$regex = ‘(?<=ConfigError=)(.*)(?=[compare Errors])’
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
但最终只能这样:
readback radio secti
甚至没有提取完整的第一行。你能帮忙吗?
答案 0 :(得分:4)
有几个问题:
Get-Content $filepath -Raw
)[
,并且[compare Errors]
被视为与集合中的单个字符匹配的字符类(您需要\[compare Errors]
)RegexOptions.Singleline
修饰符或(?s)
内联选项,以使.
在换行符之间匹配.*?
,而不是.*
才能在第一次出现[compar e Errors]
时停止使用
$regex = '(?s)(?<=ConfigError=).*?(?=\s*\[compare Errors])'
Get-Content $input_path -Raw | Select-String -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
请注意,由于您未使用子匹配项,因此我从.*?
处删除了捕获括号,并在\s*
之前添加了\[
,以从尾随空白处“修剪”结果匹配项。
正则表达式详细信息
(?s)
-单行模式,使.
跨行匹配(?<=ConfigError=)
-紧跟ConfigError
的位置.*?
-任何0个或多个字符,尽可能少(?=\s*\[compare Errors])
-在右边,必须有0+个空格,后跟[compare Errors]
。