sed stupidity or ampersand magic?

We were reformatting some code at work the other day using find and sed and stumbled upon a very weird case when using the ampersand (&) character. We accidentally expanded all boolean and expressions in our C++-code (&&) to “& &” when applying a rule to modify “<type> & <variable>” to “<type>& <variable>”. In order to change them back we ran a “find . -type f | xargs sed -i -e ’s:& &:&&:g’” which resulted in all the expression becoming “& && &”?!

After some fiddling around it turns out the ampersands in the resulting string had to be escaped to reach the desired result. As far as I know ampersands are not part of the regular expression syntax and I’ve never before had to escape anything in the resulting string.

In the end the following syntax yielded the correct result.

echo " & & " | sed -e 's:& &:\&\&:g'
 &&

I don’t know if this is a bug or feature and if anyone else does please let me know.

2 Responses to “sed stupidity or ampersand magic?”

  1. lu_zero Says:

    & means “the whole match” in sed (and other sed like applications), its explained somewhere in the man page.

    lu - yes I do refactor my code with sed too ^^

  2. dholm Says:

    Ah cwap, you are correct Luca!
    /me hides under a rock for not reading the man-page properly

    We were discussing writing a refactoring tool at work which is basically just a sed frontend. It should be fairly simple and if you can preview changes before applying it will be pretty darn powerful.

Leave a Reply