An awk
solution is also possible:
awk '{if (/^192\.168\.1\.2 /) {$0=$0 " myalias"}; print}' hosts
The above reads lines from the hosts
file one by one. If the line has our IP address at the beginning, then myalias
is appended to the line. The line is then printed to stdout
.
Note two things. There is a space after the IP address in the if
condition. Otherwise, the regex could match 192.168.1.20
etc. Also, the periods in the IP address are escaped with backslashes. Otherwise, they could match any character.
A pithier form of the solution is:
awk '/^192\.168\.1\.2 /{$0=$0 " myalias"}1' hosts