sponsor Vim development Vim logo Vim Book Ad

basic Tip #81: Substitution of characters and lines in VIM is made far easier with the s and S commands

 tip karma   Rating 30/30, Viewed by 4257 

created:   June 21, 2001 14:41      complexity:   basic
author:   Substitue characters and lines      as of Vim:   5.7

Substitute  Characters
-----------------------------------
I was just editing a file that contained the same leading string on many lines.

example:

foo_bar_baz1=a
foo_bar_baz1=abc674
foo_bar_baz1=qrs
foo_bar_baz1=m1
foo_bar_baz1=bz90
foo_bar_baz1=bc
...

Needing to only substitute a portion of the string, I referred to a VIM reference card and discovered a command answering my need exactly. The s command is used to subsitute a certain number of characters. In my example file above, if I only needed to subsititute the characters foo_bar, I set the cursor on the first character where I'd like the subsitution to begin and type 7s. VIM drops the characters foo_bar and goes to insert mode, waiting for the substitution text.

Substitute Lines
-----------------------
After years of using vi and VIM and always deleting multiple lines in order to replace them, I just discovered the S command. If you need to subsitute three lines of text, simply type 3S. VIM drops the three lines and goes into insert mode, waiting for the subsitution text.

 rate this tip  Life Changing Helpful Unfulfilling 

<<Restore cursor to file position in previous editing session | letting variable values be overwritten in a script >>

Additional Notes

leifw at bigfoot dot com, July 11, 2001 14:12
Of course, if you're lazy like me and you don't want to count that there are 7 characters that you want to replace, you could use the c command and use a motion to specify how much to kill.  For example, in the previous example, I'd type c2t_ to kill foo_bar and to be left in insert mode.
bdr at users.sourceforge.net, August 29, 2001 8:11
You could have selected the "foo_bar" characters with Ctrl+V (Visual Block), pressed "c" to change the block, made your change to the first line, press ESC and, voilą,  all the lines you selected will be changed the same way.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
    stats
Sponsored by Web Concept Group Inc. SourceForge.net Logo