154

If I run this code in bash:

echo dog dog dos | sed -r 's:dog:log:'

it gives output:

log dog dos

How can I make it replace all occurrences of dog?

Chris Seymour
  • 79,902
  • 29
  • 153
  • 193
Nishant George Agrwal
  • 1,900
  • 2
  • 11
  • 14

2 Answers2

239

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

devnull
  • 111,086
  • 29
  • 224
  • 214
Bruno Reis
  • 36,131
  • 11
  • 113
  • 152
  • 2
    Adding a corner case for GNU sed here: `sed -E 's,foo,bar,g'` doesn't do the global thing. If you change it to `sed -E -e 's,foo,bar,g'` it works. – Melvyn Sopacua Dec 12 '18 at 13:51
  • If you want to replace all on the line AND on the other lines as well it will also work: `echo 'dog dog dos\ndog'|sed 's:dog:log:g` – Timo Nov 18 '20 at 09:11
30

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^
alestanis
  • 20,883
  • 4
  • 46
  • 66
  • 1
    sed -e should be used instead of sed -r, which does not exist. – Dylan Daniels Dec 16 '15 at 01:47
  • 3
    @DylanDaniels According to `man sed` on Ubuntu, the `-r` option means "use extended regular expressions". So the given command works fine, although it doesn't need the features of extended regular expressions to work. – Craig McQueen Apr 11 '16 at 01:28