Why does sed remove the character in the example?

Viewed 140
a=a
b=ab
c=''
d=''
echo ac | sed "s/$a/$b/;"
abc
echo ac | sed "s/$a/$b/; s/$c/$d/"
bc

Why does sed remove the character 'a' in the last example?

1 Answers

It happens because the $c is an empty string, and when sed is passed the subsequent s command with an empty pattern, the previous one is used, in this case, $a, which is a.

So,

echo ac | \ 
 sed "s/$a/$b/; s/$c/$d/"
#       a  ab     a   

Here,

  • a is replaced with ab first with s/a/ab/ (ac turns into abc)
  • a is removed with s/a// (abc is turned into bc).

See documentation, the Regular Expressions in sed section:

If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

Related