I am trying to add an ampersand at the end of every line of a file using sed as follows:

sed -i -e 's/$/ &/' file

However, when I look at the contents of the file (using both Vim and just cating the file) I don't see the ampersand (only an extra space). I tried with another character 'l' and it worked. Why doesn't it work with ampersand?

1 Answer

& is one of very few characters that is special on the replacement side of a sed s/pattern/replacement/ command - in particular, it is replaced by the whole matched portion of the pattern space. In this case, the whole matched portion is a zero length assertion $, so & appears to insert nothing in the replacement.

To add a literal ampersand, you therefore need to escape it:

sed -i -e 's/$/ \&/' file 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy