shrimpy
shrimpy

Reputation: 731

Powershell - Select a specific word from text

I'm still very much learning Powershell and I'm a bit lost regarding a command to use. I have this

docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com 

and I want to select PASSWORD. Ideally, I would like this PASSWORD to get into a file, and use it after (but that I can do).

I am lost on what command to use. I know awk '{print $6}' would work but I need the powershell as I'm using a windows machine.

I know it's a really simple question, I have been reading answers, but I am just confused by the different parameters, and the different ways by different people and well, Powershell is wonderful but I'm still learning.

Thanks a lot!!

Upvotes: 0

Views: 3851

Answers (3)

user6811411
user6811411

Reputation:

Another solution using a Regular Expression,
here with lookarounds

$string = 'docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com'
if ($string -match '(?<=-p\s+).*(?=\s+-e)'){
    $Password = $Matches.Value
} else {
    "No password found"
}

Upvotes: 1

Adam
Adam

Reputation: 62

You can make this more complex :) I just used simple regexp, but you can make it better :)

$x = "docker login -u AWS -p PApSSWORD -e none number.dkr.ecr.REGION.amazonaws.com "
$x -match "(\-p[a-z0-9 ]*\-e)"
$matches[1] -replace '(\-p) ([a-z0-9 ]*) (\-e)' , ' $2'

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174920

The default field separator(s) in awk is whitespace, so we can do the same in PowerShell and then grab the 6th resulting substring.

For this, we can use the -split regex operator - it supports the following syntaxes:

[strings] -split [pattern]

or

-split [strings]

When used as in the second example above, it defaults to splitting on whitespace just like awk:

-split "docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com"

If we wrap the expression in @(), we can index into it:

$Password = @(
  -split "docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com"
)[5]

or we can use the Select-Object cmdlet to grab it:

$Password = -split "docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com" |Select-Object -Index 5

If, however, we always want to grab the substring immediately after -p instead of whatever the 6th string is, we could use the -replace regex operator instead:

$string = "docker login -u AWS -p PASSWORD -e none number.dkr.ecr.REGION.amazonaws.com"
$string -replace '^.*-p\s+(\S+).*$','$1'

Upvotes: 1

Related Questions