Question

I want to append an alias to the end of a certain line of my hosts file. For example

I have

192.168.1.1    www.address1.com
192.168.1.2    www.address2.com
192.168.1.3    www.address3.com

I want to it to look like

192.168.1.1    www.address1.com
192.168.1.2    www.address2.com myalias
192.168.1.3    www.address3.com

I want to find the line that contains 19.2.68.1.2 and append myalias at the end of it. The line is not necessarily the second line in the file like I've shown here. It could be anywhere.

Was it helpful?

Solution

Using sed and the pattern described:

sed '/192.168.1.2/s/$/ myalias/' file

Using sed and a specific line number:

sed '2s/$/ myalias/' file

OTHER TIPS

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

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..

Here is another way using awk

awk '/search pattern/{print $0 " myalias"; next}1'  file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top