Powershell Extract String Start With

Powershell Extract String Start With

I have a txt file with following content:

testdemo | 5 | 4563456| OMNI | retailomni
testRetail | 142 | 3453456345| testRetai111l | test
testtesttest | 44 | 4564356| apl | APL

I need to select whole string, that starts from "testdemo". How this can be done in PS?

$operator = "testdemo"
$operatorcontent = Get-Content operators.txt | "Need to get whole string, starts from $operator"    

3 Answers

    Get-Content operators.txt | Select-String -Pattern "testdemo"

Will select if the line contains testdemo anywhere in the line

If you want to select lines that that starts with testdemo

    Get-Content operators.txt | Select-String -Pattern "^testdemo"

You can use Select-String cmdlet.

Get-Content operators.txt | Select-String -Pattern "testdemo"

More about Select-String --> Get-Help Select-String -Online

Get-Content operators.txt | ForEach-Object {
    if($_ -match "testdemo"){
        $_
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.