Patrick
Patrick

Reputation: 8063

Bash grep IP from command output

I'm working with fleetctl and kubectl and would like to extract an IP from kubectl get pod app-etcd:

POD        IP           CONTAINER(S)   IMAGE(S)                     HOST                               LABELS          STATUS    CREATED   MESSAGE
app-etcd   10.10.0.1                                               k8s-socius-node-1/100.100.100.100   name=app-etcd   Running   3 days    
                        app-etcd       xyz/etcd-discovery                                                      Running   3 days

The closest I got to get the IP address is:

kubectl get pod app-etcd | grep -Eo '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'

But this gives me both IP addresses (10.10.0.1 and 100.100.100.100); I only want/need the first one to run sed over a config file afterwards.

How do I get only the first address to store it in a variable for further processing?

Upvotes: 1

Views: 1062

Answers (2)

Patrick
Patrick

Reputation: 8063

kubectl offers json output with --output / -o:

kubectl get -o json pod app-etcd | jsawk 'return this.status.podIP'

Upvotes: 1

Rahul
Rahul

Reputation: 77876

What if you use awk to get the second column output like

kubectl get pod app-etcd | awk '{print $2}'

Upvotes: 2

Related Questions