I am trying to parse a file for IP addresses and then replace them with a 1 for 1 mapped IP address. For example, find all instances of 1.1.1.1 and replace these with 100.100.1.1, and all instances of 5.5.5.5 and replace those with 100.100.5.5. There may be thousands of IPs, so I do not want to parse the file for each substitution using static sed commands.
I am trying to use an associative array for this, but I am falling short.
echo "1.1.1.1 5.5.5.5" > testfile.txt
declare -A testarray
testarray[ip_1.1.1.1]="100.100.1.1"
testarray[ip_5.5.5.5]="100.100.5.5"
sed -r "s/(([0-9]{1,3}\.){3}[0-9]{1,3})/${testarray[ip_\1]}/g" testfile.txt
Using the capture group inside the variable doesn't work. However using the text directly does.
sed -r "s/(([0-9]{1,3}\.){3}[0-9]{1,3})/${testarray[ip_1.1.1.1]}/g" testfile.txt
100.100.1.1 100.100.1.1
Of course this replaces all IPs with 100.100.1.1, I want to replace based on the array association.
Is there any way to take a capture group and use it in a variable for a replacement in bash? I have tried a few variants with quotes as well as building a variable in advance that still depends on '\1' but it either fails, or just returns the literal output of the variable. I don't know if there is a better tool than sed for this. I also tried using variables instead of an array, but I ran into the same issue.