Why does sed not replace all occurrences?

BashSed

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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/

Solution 2 - Bash

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNishant George AgrwalView Question on Stackoverflow
Solution 1 - BashBruno ReisView Answer on Stackoverflow
Solution 2 - BashalestanisView Answer on Stackoverflow