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.

I would go with awk, since you can use strings and do not have to use regex, where dots would need to be escaped and anchors and/or word boundaries would need to be used. Also you can make sure the string matches a value in column 1.

awk '$1==s{$0=$0 OFS alias}1' s=192.168.1.2 alias=myalias file

Also when it is part of a larger script, it is nice to be able to use variable strings. With sed you would need shell variables and quote trickery..