170

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
  • 83,387
  • 30
  • 160
  • 202
Nishant George Agrwal
  • 2,059
  • 2
  • 12
  • 14

2 Answers2

262

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
  • 118,548
  • 33
  • 236
  • 227
Bruno Reis
  • 37,201
  • 11
  • 119
  • 156
  • 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
39

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

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^
alestanis
  • 21,519
  • 4
  • 48
  • 67
  • 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