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
- get the one with TARGET contains
targetPools
- extract the IP_ADRESS
- store in local variable to be used
But not sure how to do this, any hints?
CodePudding user response:
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
andstdout
.-FB2
is a shorthand for-F
-B 2
- See
grep --help | grep -- -B
- See
grep --help | grep -- -F
- See
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
CodePudding user response:
Using awk
:
gcloud ... 2>&1 | awk -F: 'BEGIN {RS=""} $10 ~ /targetPools/ {print $6}'