使用正则表达式与 Powershell ForEach 替换

时间:2021-05-03 14:02:20

标签: regex powershell replace foreach

我需要替换日志文件一行中的一些字符。

此日志文件的一部分定义为:

(sha1: b2ac534797bceb683ee5db85fcd4bbb885c4a205, md5: bb4fd7d270c523bb5d1c6c18e9b42801, sha256: e5b9090d2f0efd5aa99102aae223b4e346c6c8229d4931d08bbb5d1d43146cfd)

我想用一个简单的 ;

替换整个字符串
ForEach {$_ -replace "\' (SHA-1:^[a-z][0-9]$ , MD5:^[a-z][0-9]$ , SHA-256:^[a-z][0-9]$ ",";"}

但这行不通。获取消息,模式无效。

1 个答案:

答案 0 :(得分:2)

目标字符串可以描述为(...),其中...是一个由<algoName>: <hash>和一个可选的尾随序列, 组成的组,重复3次:

$replaced = Get-Content path\to\file.log |ForEach-Object {
  $_ -replace '\(((sha|md)\d+: [a-f0-9]+(, )?)+\)', ';'
}

$replaced |Set-Content path\to\output.txt

如果日志文件比较小(例如KBs而不是MBs),你也可以直接将-replace应用于Get-Content的输出:

@(Get-Content path\to\file.log) -replace '\(((sha|md)\d+: [a-f0-9]+(, )?)+\)', ';' |Set-Content path\to\output.txt