Go back to the main page

Vim search and replace on only one line

 

I always thought the /g modifier meant to globally replace the entire document. However, it really means to globally replace on 1 line. The common % in, for example, %s/the/The/g means to replace on each line of the entire document, not the /g modifier. Therefore:

# Example document
1 the the and The
2 the and the
3 end the
# If our cursor was on line 1 and we did:
:s/the/The/g
# that would replace just the first line.
# If we did:
:s/the/The 
# that would just replace the first match of "the"
# If we did:
:%s/the/The
# that would match the first "the" on each line
# If we did:
:%s/the/The/g
# that would replace each line and each "the"
  • Pushed on 02/27/2012 by Christian