Select-String - 查找跨越多行的字符串 [英] Select-String - find a string that spans multiple lines

查看:78
本文介绍了Select-String - 查找跨越多行的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取文件中的行并搜索跨越两行的模式.在记事本++中查看文件,我看到文件中有一个 LF 字符.

示例日志.txt:

<前>我想找到这个这里的价值:好的

我的简单代码不起作用并且什么都不返回:

select-string -Path "log.txt" -Pattern "find this\n*value here: OK"

我在这里尝试了多种组合,包括 .+\r ,我发现它们发布在各种线程上.我可以使用以下方法获取第一行:

select-string -Path "log.txt" -Pattern "find this\n*"

上面的结果是:我想找到这个

向上面的行添加更多内容不会返回任何内容.任何想法如何使用选择字符串来做到这一点?由于我正在处理的文件的潜在大小,我试图避免使用 get content.

解决方案

所以我想我明白你的问题了.如果您的文件中有一行要关闭,那么下一行就是您要查看的行:

(Select-String -Path "Log.txt" -Pattern "find this" -Context 1).Context.PostContext

我不确定那个回车是否是你格式化的产物.如果不是,那么这会更好:

(Select-String -Path "Log.txt" -Pattern "find this" -Context 2).Context.PostContext[1]

如果您不知道两个位之间有多少行,这里有一种方法:

$file = Get-Content 'Log.txt' -Raw$file -match '(?smi)I want to find this.*(value here: OK)'$匹配[1]

I am trying to read lines in a file and search for a pattern that spans two lines. Looking at the file in notepad++ I see a LF char in the file.

Example log.txt:

I want to find this

value here: OK

My simple code does not work and returns nothing:

select-string -Path "log.txt" -Pattern "find this\n*value here: OK"

I have tried many combos of various things here including .+ and \r that I found posted on various threads. I can get the first line by using:

select-string -Path "log.txt" -Pattern "find this\n*"

Result of above is: I want to find this

Adding anything more to the line above results in nothing being returned. Any ideas how to do this using select-string? I was trying to avoid using get content due to the potential size of the files I am working with.

解决方案

So I think I understand your question. If you have a file that has a line that you want to key off of then the next line is the line that you want to look at:

(Select-String -Path "Log.txt" -Pattern "find this" -Context 1).Context.PostContext

I wasn't sure if that carriage return was an artifact of your formatting or not. If it is not then this would work better:

(Select-String -Path "Log.txt" -Pattern "find this" -Context 2).Context.PostContext[1]

Here is a way to do it if you don't know how many lines will be between the two bits:

$file = Get-Content 'Log.txt' -Raw
$file -match '(?smi)I want to find this.*(value here: OK)'
$matches[1]

这篇关于Select-String - 查找跨越多行的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆