sed Pattern flags - occurrence replacement


Example

If we want to replace only the first occurrence in a line, we use sed as usual:

$ cat example
aaaaabbbbb
aaaaaccccc
aaaaaddddd
$ sed 's/a/x/' example
xaaaabbbbb
xaaaaccccc
xaaaaddddd

But what if we want to replace all occurrences?

We just add the g pattern flag at the end:

$ sed 's/a/x/g' example
xxxxxbbbbb
xxxxxccccc
xxxxxddddd

And if we want to replace one specific occurrence, we can actually specify which one:

$ sed 's/a/x/3' example
aaxaabbbbb
aaxaaccccc
aaxaaddddd

/3 being the 3rd occurrence.


GNU sed

From info sed, see GNU sed manual for online version

the POSIX standard does not specify what should happen when you mix the g and NUMBER modifiers, and currently there is no widely agreed upon meaning across sed implementations. For GNU sed, the interaction is defined to be: ignore matches before the NUMBERth, and then match and replace all matches from the NUMBERth on.

$ sed 's/b/y/2g' example
aaaaabyyyy
aaaaaccccc
aaaaaddddd

$ sed 's/c/z/g3' example
aaaaabbbbb
aaaaacczzz
aaaaaddddd