Reputation: 57
I have to replace an IP in a script so I used a variable to store the output of awk like for instance:
existing_ip=$(awk --field-separator '=' '/10.171.0.231/ { print $2; }' file.txt)
On the other hand I am also taking user input like:
read -p "What is the IP address to be replace: " new_ip
echo -e "New IP: ${new_ip}"
Now in the next step I am facing an issue when I try to replace the IP with sed or awk command. I have tried using the below commands but none worked.
awk -v s="$existing_ip" '{gsub(/10.171.[0-9].{1,3}.[0-9]/, s)}1'
sed -i "s/${existing_ip}/${new_ip}/g"
Help will be greatly appreciated.
Upvotes: 0
Views: 697
Reputation: 163297
Apart from mentioned in the comment that you have to specify an input file, the pattern 10.171.[0-9].{1,3}.[0-9]
can match for example 10a171b0cdef2
as you have to escape the dot to match it literally.
If you escape the dot, the quantifier {1,3}
would go after matching a digit at the end. So you would match a single digit in the 3rd part, and 1-3 digits in the 4th part.
cat file.txt
This is ip 10.171.1.111 and this is ip 10.172.0.231
For example
existing_ip="10.171.0.231"
awk -v s="$existing_ip" '{gsub(/10\.171\.[0-9]\.[0-9]{1,3}/, s)}1' file.txt
Output
This is ip 10.171.0.231 and this is ip 10.172.0.231
Upvotes: 1