Append text at the end of a specific line

Posted on

Problem :

I have a file with multiple lines. What I am trying to accomplish is add a string at the end of a commando.

I have a script that installs a tool automatically. Now some things have changes in the sources.
I need to add contrib non-free at the end of this line:

deb wheezy main

It should look at this:

deb wheezy main contrib non-free

How can I accomplish this?

Solution :

Since you’re using Linux, you’ll have the GNU version of sed (which has an -i option for ‘in-place’ editing of files):

sed -i '/deb main/s/$/ contrib non-free/'

In the sed command, the stuff between the first two // tells sed to search for a line containing that — so sed '/foo/' would search for lines containing ‘foo’. Because your line contains forward-slashes, those need to be escaped. the s/$/ contrib non-free tells sed to replace the end of the line (represented by the dollar sign) with ‘ contrib non-free’. The general form is s/replace this/with this/. Taken together, this searches for the lines you want and then tacks your text onto the end.

If you just want to alter the end of every line in the file:

sed -i 's/$/ contrib non-free/'

Using the standard text editor, ed, is very slightly more portable, but in general you’ll find yourself using sed for these tasks more often (or, preferably, a decent text editor such as vim).

printf '%sn' 'g/deb main/s/$/ contrib non-free/' w q | ed

Leave a Reply

Your email address will not be published. Required fields are marked *