我有一个日志文件,其中有数万行,我需要关键字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
但不能得到正确的结果。
Update1
使用(?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:
发布于 2021-12-13 19:11:35
根据你最新的问题,基本上一切都很好。
如果要在字符串中展开变量,则需要使用双引号字符串而不是单引号。
因此,regex语句如下:
$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在线测试工具。在你得到你想要的东西之前,它们对你的regex语句非常实用。这不会解决你的报价问题(单引号和双引号),但会帮助你找到正确的regex语句,并在实验中看到结果。
参考文献:
单引号字符串 以单引号括起来的字符串是逐字字符串.当您键入字符串时,该字符串将完全传递给命令。不执行替换。 双引号字符串 以双引号括起来的字符串是可扩展的字符串。在将字符串传递给命令进行处理之前,前面有美元符号($)的变量名被替换为变量的值。
在线判读测试器(https://regexstorm.net/tester)
https://stackoverflow.com/questions/70330676
复制相似问题