I'm trying to use sed to find a line containing a string after an IP address and replace that line. To illustrate, I have a text file like so ...
192.168.10.155 Mike
8.8.8.8 Googley
123.231.123.3 Tom
192.238.8.10 Matt
Let's say I want to find and replace Tom's line, and I want to match on a Tom AFTER an IP address and a space. Each octet of the IP address could have between 1 and 3 digits. Currently, I have ...
newIpAddress="111.111.111.111"
sed -i "/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} Tom/c\$newIpAddress Tom" file
But this doesn't seem to work. Any ideas as to how I could fix that first part to properly match dynamically on any IP address with 1 to 3 digits per octet?
Here is the awk
approach:
$ new_ip=1.1.1.1
$ awk -v ip="$new_ip" '$2=="Tom"{$1=ip}1' file
192.168.10.155 Mike
8.8.8.8 Googley
1.1.1.1 Tom
192.238.8.10 Matt
sed -ri "/[0-9]{1,3}(\.[0-9]{1,3}){3} Tom$/c$newip Tom" file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.