Powershell在两个字符串之间匹配多行字符

时间:2020-05-13 16:35:37

标签: regex powershell

我不知道如何从日志文件中提取所有内容(多行)。这是我需要从中提取的示例:

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

甚至没有提取完整的第一行。你能帮忙吗?

1 个答案:

答案 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]