1

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

  1. get the one with TARGET contains targetPools
  2. extract the IP_ADRESS
  3. store in local variable to be used

But not sure how to do this, any hints?

Peter
  • 544
  • 5
  • 20
  • 1
    `gcloud ... 2>&1 | grep -FB2 'TARGET: us/targetPools/efg' | head -n1 | sed 's/^.*: *//'` – Jetchisel Jan 10 '23 at 00:30
  • 1
    it worked, thanks @Jetchisel. please post as the answer explaining the command and I will accept it – Peter Jan 10 '23 at 00:42

2 Answers2

2

Using awk:

gcloud ... 2>&1 | awk -F: 'BEGIN {RS=""} $10 ~ /targetPools/ {print $6}'
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
1

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

    • See grep --help | grep -- -B
    • See 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

Jetchisel
  • 7,493
  • 2
  • 19
  • 18
  • 1
    Hi @Jetchisel, would you be able to explain what `grep -FB2` does? Also explain a little bit what the `sed regular expression` is doing? Thanks a lot – Peter Jan 10 '23 at 00:53