首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用power shell基于关键字读取文件内容?

如何使用power shell基于关键字读取文件内容?
EN

Stack Overflow用户
提问于 2021-12-13 06:25:29
回答 1查看 78关注 0票数 0

我有一个日志文件,其中有数万行,我需要关键字A和B之间的这些内容。关键字A和B在文件中是唯一的。如何通过power shell脚本获取内容并将内容保存到新文件中?如有任何建议,敬请见谅。谢谢。

输入数据可以如下所示:

代码语言:javascript
运行
复制
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

我试过的

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
$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应该是一个句子,现在,我将脚本更改为

代码语言:javascript
运行
复制
$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

它没有返回结果。

代码语言:javascript
运行
复制
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:
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-13 19:11:35

根据你最新的问题,基本上一切都很好。

如果要在字符串中展开变量,则需要使用双引号字符串而不是单引号。

因此,regex语句如下:

代码语言:javascript
运行
复制
$A= 'DUMP OF SERVICE batterystats:'
$B = 'Per-PID Stats:'
#Write-Host $text
$regex = '(?ms)$A\n(.+?)$B\n?'

需要改为:

代码语言:javascript
运行
复制
"(?ms)$A\n(.+?)$B\n?"

注意:

您应该看看一些.net regex在线测试工具。在你得到你想要的东西之前,它们对你的regex语句非常实用。这不会解决你的报价问题(单引号和双引号),但会帮助你找到正确的regex语句,并在实验中看到结果。

参考文献:

关于引用规则

单引号字符串 以单引号括起来的字符串是逐字字符串.当您键入字符串时,该字符串将完全传递给命令。不执行替换。 双引号字符串 以双引号括起来的字符串是可扩展的字符串。在将字符串传递给命令进行处理之前,前面有美元符号($)的变量名被替换为变量的值。

在线判读测试器(https://regexstorm.net/tester)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70330676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档