-1

When I search and replace a string, it only replaces the first occurrence every line:

1,4 -> 1,4 : a
1,4 --> 2 : b
1,4 --> 6 : c

:%s/,/_

1_4 -> 1,4 : a
1_4 --> 2 : b
1_4 --> 6 : c

Why is this happening? How do I replace all occurences? Why is this the default behavior in vim?

jeffrey.d.m
  • 616
  • 8
  • 23

1 Answers1

2

TL;DR: :%s/search/replace/g

This is the intended way that the search and replace is supposed to work: :<range>s/<search>/<replace>[/g]. You give a range, the search string, and the replacement string. At the end you can optionally specify /g to replace all occurrences on each line.

If this isn't the default behavior you want, you can also change this in your .vimrc: set gdefault. This will change search and replace to act like there is always the /g flag present, or better said, inverts the g flag. This means that if you ever need to only replace one occurrence on a line, add the /g again.

https://www.linux.com/training-tutorials/vim-tips-basics-search-and-replace/ https://stackoverflow.com/a/13679358/12393574

jeffrey.d.m
  • 616
  • 8
  • 23