我想通过在PowerShell中读取文件的每一行来提取两个字符串之一。
例:desc.txt
包含:
Description : Attaching new instance: inst-id
Description : Detaching new instance: inst-id
Description : Launching new instance: inst-id
我想逐行读取desc.txt,如果该行具有“附加”或“启动”,则选择inst-id。
我可以通过以下代码在两个字符串中仅提取一个字符串:
$b=Get-Content .\desc.txt
$b | Select-String -SimpleMatch "Launching"
输出:
Description : Launching a instance: inst-id
最佳答案
如果要匹配多个字符串,则需要使用正则表达式。根据description of Select-String,参数-SimpleMatch不支持正则表达式。因此,您需要使用-Pattern参数。
这是同时匹配“启动”和“附加”的完整示例:
$FileName = [System.IO.Path]::GetTempFileName()
@"
Description : Attaching new instance: inst-id
Description : Detaching new instance: inst-id
Description : Launching new instance: inst-id
"@ | Out-File -FilePath $FileName
Get-Content -Path $FileName | Select-String -Pattern "Attaching|Launching"
Remove-Item -Path $FileName
关于powershell - 从文件中选取两个字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27763624/