2

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?

terdon
  • 242,166

1 Answers1

4

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.

So:

sed -i 's/s&/l\&/g' file.txt
Iggy B
  • 144
  • 1
    not needed in the left hand side. – don_crissti Mar 02 '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 02 '17 at 12:07