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.
You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.
To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.
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
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With