Another way to append a text in sed using ampersand

Written by - 3 comments

Published on August 15th 2018 - Listed in Linux Shell Bash Coding


I love such situations when I accidentally stumble across something which turns out to be cool and pretty useful!

I wanted to replace an umlaut (ö) in a text file with the html equivalent (ö):

# cat /tmp/xxx.html
This is a text containing an ö umlaut.
Because in German we use ä ö ü.

For this I wanted to use a simple sed command:

# cat /tmp/xxx.html | sed "s/ö/ö/g"
This is a text containing an öouml; umlaut.
Because in German we use ä öouml; ü.

As you can see above, instead of replacing all ö's, the character was appended by 'ouml;'.

Turns out that the ampersand (&) has a special meaning in sed and is, in this case, being used to "append characters after found element".

Practical example:

# cat /tmp/xxx.html | sed "s/text/& I wrote myself/g"
This is a text I wrote myself containing an ö umlaut.
Because in German we use ä ö ü.

Can be quite handy actually!

To achieve my original goal (replace ö) the special ampersand character needs to be escaped:

# cat /tmp/xxx.html | sed "s/ö/\ö/g"
This is a text containing an ö umlaut.
Because in German we use ä ö ü.



Add a comment

Show form to leave a comment

Comments (newest first)

Kristian from wrote on Jul 4th, 2020:

ck, thank you for your answer. It was indeed my fault (and I think it was simply to late to work).

My aim was to add an ampersand to the text, something like
bla -> bla & bla2

I tried it later with \& and this worked unter Windows like on Linux
> sed "s/bla/bla \& bla2/g"

My fault was that I thought I had to escape the & character for Windows also. Sometime sed is not easy on Windows because of some special characters one has to escape.


ck from Switzerland wrote on Jul 3rd, 2020:

Kristian, maybe sed on Windows behaves differently? I do not know honestly. I don't know what you want to achieve, either. If you simply want to add an ampersand character at the beginning of your lines, on Linux you would probably use sed "s/^/\&/g".


Kristian from wrote on Jul 3rd, 2020:

I am actually in the same situation but on Windows. And just making an & to \& in the RHS part does not help here. I tried to change to ^& and \^&, but none of them got me to the result I want...

Do you have an idea?