powershell - 如何匹配txt文件中的3行并在中间行提取字符串
问题描述
使用 Powershell 我想从文本文件中提取一个值,该值位于与模式匹配的两行之间。
我正在尝试匹配 3 行,第 1 行和第 3 行将始终相同:
1st: ' 1'
2nd: trying to read... always 2-4 characters
3rd: ' 40'
在很多情况下,第 1 行和第 3 行应该与此匹配。
我尝试使用以下代码。
$aa=Get-Content $filename1 -Raw
$aaa=$aa |Where-Object { ( $_ -match '(.\s1)(?:\r\n|[\r\n])*(?:\r\n|[\r\n])(\s40)') }
$aaa
我得到了太多的输出......也许它只匹配第 1 行和第 3 行以及介于两者之间的许多行。
解决方案
您可以使用正则表达式来做到这一点:
$regex = [regex] '\s+1\r?\n(?<secondline>.*)\r?\n\s+40'
$match = $regex.Match($text)
$result = while ($match.Success) {
$match.Groups['secondline'].Value
$match = $match.NextMatch()
}
$result
$text
您阅读的文件在哪里$text = Get-Content 'FILENAME' -Raw
:
1 trying to read... always 2-4 characters 40 1 another second line 40 1 the line you are interested in 40
结果是
trying to read... always 2-4 characters
another second line
the line you are interested in
推荐阅读
- r - 非线性趋势
- python - 在python的嵌套列表中创建嵌套列表
- mysql - 如何用颤振制作一个mysql实时数据库?
- actionscript-3 - 使用 POST 的独立 Flash 播放器 navigateToURL 失败
- ios - iPhone 不可用
- python-3.x - 在 django 石墨烯中似乎没有调用 model.UUIDField() 的默认值
- reactjs - 如何在 React Native 中使用带有 RNPickerSelect 的 React Hook Form?
- python - 时间序列平稳技术
- typescript - 如何使用默认值从打字稿文件中导出所有功能?
- reactjs - 创建用户后如何将数据添加到firestore文档