Skip to content
Advertisement

How to print IP address from Shell Script?

Below is my command line

$ps -eaf | grep consul_exporter | grep -v grep
root      4020     1  6 Mar20 ?        4-08:51:18 ./consul_exporter --consul.server=10.1.2.133:8500 --kv.prefix=/ --web.listen-address=0.0.0.0:80

I want to get output of IP address(10.1.2.133) alone as output. How to write command line for that?

Advertisement

Answer

If you don’t mind a solution which is not elegant, but does the job, just pipe the output of your grep command into

... | cut -f 2 -d = | cut -f 1 -d :

This splits the line first by the = and then :. If the pattern is not so regular and the IP address can appear anywhere in the line, pipe it into

... | grep -oE '([0-9]{1,3}[.]){3}[0-9]{1,3}'

The -o option just extract the matching pattern(s) from the input.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement