Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

Choose a particular string from text file using Powershell

Hi I have a file with below content


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

I want to fetch a particular keyword ASGonline-sys-system1-asg from this. but whenever I am trying to run below commands it is giving wrong output:


    PS C:Windowssystem32> Select-String -Path C:empinstancename.txt -pattern 'ASGonline-sys-system1-asg'
    
    > C:empinstancename.txt:26:TAGS    Name    ASGonline-sys-system1-asg
    > C:empinstancename.txt:31:TAGS    aws:autoscaling:groupName    ASGonline-sys-system1-asg20210107040213164400000001

I tried another command as well Get-Content but seems same output only I am getting:


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

I know it's a silly question but any mean I will get the output only ASGonline-sys-system1-asg

Whatever the name in the file comes it needs to give me that output only


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

!?

param(
    $exampleFileName = "d:mpfile.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

Forgive me my English, as I understand it, you want to get the substring "ASGonline-sys-system1-asg" from the file's content. this can be done by reading the contents of the file into a variable and applying regular expressions to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...