How to extract the IP address of the output of the gcloud
command mentioned bellow?
The goal is to extract the IP_ADRESS where TARGET contains targetPools
and store it in a variable.
$ gcloud compute forwarding-rules list
>output:
NAME: abc
REGION: us
IP_ADDRESS: 00.000.000.000
IP_PROTOCOL: abc
TARGET: us/backendServices/abc
NAME: efg
REGION: us
IP_ADDRESS: 11.111.111.111
IP_PROTOCOL: efg
TARGET: us/targetPools/efg
desired output:
IP="11.111.111.111"
my attempt:
IP=$(gcloud compute forwarding-rules list | grep "IP_ADDRESS")
it doesn't work bc it need to
targetPools
But not sure how to do this, any hints?
With your given input, you could chain a few commands with pipes. That means there is always one line of text/string in between TARGET
and IP_ADDRESS
.
gcloud ... 2>&1 | grep -FB2 'TARGET: us/targetPools/efg' | head -n1 | sed 's/^.*: *//'
You could do without the head
, something like
gcloud ... 2>&1 | grep -FB2 'TARGET: us/targetPools/efg' | sed 's/^.*: *//;q'
Some code explanation.
2>&1
Is a form of shell redirection, it is there to capturestderr
and stdout
.
-FB2
is a shorthand for -F
-B 2
grep --help | grep -- -B
grep --help | grep -- -F
sed 's/^.*: *//'
^
Is what they call an anchor, it means from the start.
.*
Means zero or more character/string.
.
Will match a single string/character
*
Is what they call a quantifier, will match zero or more character string
:
Is a literal :
in this context
*
Will match a space, (zero or more)
//
Remove what ever is/was matched by the pattern.
q
means quit, without it sed
will print/output all the lines that was matched by grep