powershell - 在 Powershell 中使用 Select-String 方法获取字符串
问题描述
我有很多这样的文本文件,下面是一个此类文件的示例。这是文件 File_Content12 的一部分。
name:duplicate1-content:philips -sequence:primary...........
name:guard1-content:sony -sequence:primary...........
name:Linux-content:sony -sequence:third...........
name:Windows-content:IPS -sequence:secondary...........
name:Notebook-content:Mark -sequence:fourth...........
name:duplicate1-content:Tony -sequence:primary...........
当内容是索尼时,我正在编写一个 powershell 代码来获取名称 duplicate1。
我编写了下面的代码,它会获取有关文件中存在哪些内容、行号以及行的信息。
$contents = 'sony','Philips'
ForEach ($ct in $contents)
{
Get-Childitem -Path "D:\Input\Files\" | Select-String -Pattern "$ct" | Select Filename,LineNumber,Line,@{n='Content';e={$ct}}
}
当内容是索尼时,我被困在这部分以获得名称 duplicate1。我是否需要使用 IndexOf 和 Substring 来获取值,或者是否有任何其他方式来获取此名称。
解决方案
Select-String
使用正则表达式,所以duplicate.*sony
应该做你需要的
$contents = 'duplicate.*sony','Philips'
ForEach ($ct in $contents)
{
Get-Childitem -Path "D:\Input\Files\" | Select-String -Pattern "$ct" | Select Filename,LineNumber,Line,@{n='Content';e={$ct}}
}
运行Get-Help about_Regular_Expressions
以获取更多详细信息
推荐阅读
- json - Flutter:如何映射字典?通过字典制作下拉选项
- json - 使用 Moshi 处理可能是列表或自定义对象的 JSON 响应
- javascript - 点击时如何从表单中获取数据?
- amazon-web-services - api 网关与 aws 批处理集成
- visual-studio - 签入策略 Visual Studio - 如果在定义的模板中,则检查变更集注释
- java - 启动 Tomcat 时 JavaMelody 抛出 NullPointerException
- python - 如何更改连接器形状连接到其他形状时的外观?
- angular - 在与 TemplateRef 相同的组件中访问 Angular ng-template
- java - 与面向对象的方法作斗争
- java - Spring注解方法用途