linuxsedand-operator

Fix formatting of && operator with sed


I am trying to write a sed command that adds one space to either side of the && (AND) operator. This is what I have so far:

sed -E 's+(\&\&)|(\s*\&\&\s*)+ & +g test.c

The first condition of no spaces around the && works, so

if(numberIn==0&&char=='g')

becomes

if(numberIn==0 && char=='g')

But the second condition of 1 or more spaces doesn't work. So this

if(numberIn==0  &&   char=='g')

doesn't change.

The pattern of \s*OPERATOR\s* worked with other binary operators so I'm not sure why it's not working on the and operator. Am I missing something about using sed on the and operator? With the first condition, I noticed that if you replace it with " && " you actually get " && &&" so that's why the substitute pattern is " & ". (This wasn't the case with the OR or EQUALS operators).

Any tips would be appreciated.


Solution

  • & in a sed replacement means "insert the matched string".

    Use \& to insert a literal ampersand:

    $ echo 'foo   && bar' | sed -E 's+(\&\&)|(\s*\&\&\s*)+ \&\& +g'
    foo && bar
    

    PS: Get a real code formatted like clang-format.