This question already has an answer here:

I have a simple text of URLs in stdout. Part of the URL looks as below.

https://somedomain./xx?t=s&u=random other text

I wish to change this using sed or something from the command line to read

https://somedomain./xx?t=l&u=random other text

I have used sed -e 's/s&/l&/'

Instead of replacing s& with l& I am getting ls& in the string. Is there something wrong with my command?

marked as duplicate by don_crissti, terdon Mar 2 '17 at 12:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You must escape the "&" character on the right-hand side of the s command by adding a "\" before it. Without it, "&" is special and is replaced by what is matched by the regular expression. On the left hand side, "&" is not special and is guaranteed to be non-special. You don't want to escape it as while & would never be special, \& is not guaranteed to be and what it matches is unspecified.


sed -i 's/s&/l\&/g' file.txt
  • 1
    not needed in the left hand side. – don_crissti Mar 2 '17 at 12:02
  • 1
    @don_crissti, not only it's not needed, but it's also better to avoid it as while & is guaranteed to be non-special on the lhs, the behaviour for \& is unspecified, some implementations may treat it specially (if not now, maybe in a future version). – Stéphane Chazelas Mar 2 '17 at 12:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.