Search code examples
linuxbashparsingip-address

How to get all of the IP addresses in a string into a bash array


I have the following string:

redis. 600 IN A 172.16.0.3 redis. 600 IN A 172.16.0.4 redis. 600 IN A 172.16.0.5 redis. 600 IN A 172.16.0.6 redis. 600 IN A 172.16.0.7

The string is obtained from the following command:

dig redis A | grep redis | grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

The string is printed out on each line when the command is run, but I save the output to a variable so it's all one line. I want to get all of the IP addresses into a bash array. What's the best way for me to do this?

Edit: This post is not a duplicate because the focus of this was how to get the IP addresses, not how to read them into the array.


Solution

  • I ended up being able to do it by using awk:

    IPAddresses=($(dig redis A | grep redis | grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | awk '{print $5}'))
    

    The IPAddresses array has all of the IP addresses in it, and can be printed out by executing echo "${IPAddresses[@]}"