首页 > 解决方案 > 使用 Powershell 从文本文件中选择特定字符串

问题描述

嗨,我有一个包含以下内容的文件


    TAGS    Name    ASGonline-sys-system1-asg
    TAGS    aws:autoscaling:groupName   ASGonline-sys-system1-asg20210107040213164400000001

我想从中获取一个特定的关键字ASGonline-sys-system1-asg。但是每当我尝试在命令下运行时,它都会给出错误的输出:


    PS C:\Windows\system32> Select-String -Path C:\temp\instancename.txt -pattern 'ASGonline-sys-system1-asg'
    
    > C:\temp\instancename.txt:26:TAGS    Name    ASGonline-sys-system1-asg
    > C:\temp\instancename.txt:31:TAGS    aws:autoscaling:groupName    ASGonline-sys-system1-asg20210107040213164400000001

我也尝试了另一个命令 Get-Content 但似乎只有我得到的输出相同:


    PS C:\Windows\system32> Get-Content C:\temp\instancename.txt | Where-Object { $_.Contains("ASGonline-sys-system1-asg") }
    TAGS    Name    ASGonline-sys-system1-asg
    TAGS    aws:autoscaling:groupName   ASGonline-sys-system1-asg20210107040213164400000001

我知道这是一个愚蠢的问题,但无论如何我只会得到输出ASGonline-sys-system1-asg

无论文件中的名称是什么,它只需要给我那个输出

标签: powershell

解决方案


!?

param(
    $exampleFileName = "d:\tmp\file.txt",
    $pattern         = "ASGonline-sys-system1-asg"
)

$PSVersionTable.PSVersion

@"
TAGS    Name    ASGonline-sys-system1-asg
TAGS    aws:autoscaling:groupName   ASGonline-sys-system1-asg20210107040213164400000001
"@ | Out-File $exampleFileName

$fileContent = Get-Content $exampleFileName -Raw

([regex]::Matches($fileContent, $pattern))[0].Value

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      1      0
ASGonline-sys-system1-asg

请原谅我的英语,据我了解,您想从文件内容中获取子字符串“ASGonline-sys-system1-asg”。这可以通过将文件的内容读入变量并对其应用正则表达式来完成。


推荐阅读