Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a string at end of a specific line in a file in bash [duplicate]

Tags:

bash

sed

awk

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.

like image 598
Chris F Avatar asked Mar 03 '14 22:03

Chris F


People also ask

How do I append a string to the end of a file in Linux?

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.

How do I append to the end of a file in bash?

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.


3 Answers

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
like image 172
Steve Avatar answered Oct 07 '22 10:10

Steve


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
like image 42
John1024 Avatar answered Oct 07 '22 10:10

John1024


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

like image 43
Scrutinizer Avatar answered Oct 07 '22 10:10

Scrutinizer