Vim: insert the same characters across multiple lines

后端 未结 12 1879
慢半拍i
慢半拍i 2020-11-29 14:23

Sometimes I want to edit a certain visual block of text across multiple lines.

For example, I would take a text that looks like this:

name
comment
ph         


        
相关标签:
12条回答
  • 2020-11-29 14:37

    Updated January 2016

    Whilst the accepted answer is a great solution, this is actually slightly fewer keystrokes, and scales better - based in principle on the accepted answer.

    1. Move the cursor to the n in name.
    2. Enter visual block mode (ctrlv).
    3. Press 3j
    4. Press I.
    5. Type in vendor_.
    6. Press esc.

    Note, this has fewer keystrokes than the accepted answer provided (compare Step 3). We just count the number of j actions to perform.

    If you have line numbers enabled (as illustrated above), and know the line number you wish to move to, then step 3 can be changed to #G where # is the wanted line number.

    In our example above, this would be 4G. However when dealing with just a few line numbers an explicit count works well.

    0 讨论(0)
  • :%s/^/vendor_/
    

    or am I missing something?

    0 讨论(0)
  • 2020-11-29 14:42

    Suppose you have this file:

    something
    
    name
    comment
    phone
    email
    
    something else
    and more ...
    

    You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.

    :%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
    

    The c flag will prompt you for confirmation. You can drop that if you don't want the prompt.

    0 讨论(0)
  • 2020-11-29 14:44
    1. Ctrl + v to go to visual block mode
    2. Select the lines using the up and down arrow
    3. Enter lowercase 3i (press lowercase I three times)
    4. I (press capital I. That will take you into insert mode.)
    5. Write the text you want to add
    6. Esc
    7. Press the down arrow
    0 讨论(0)
  • 2020-11-29 14:45
    Use Ctrl+V to enter visual block mode
    Move Up/Down to select the columns of text in the lines you want to comment.
    Then hit Shift+i and type the text you want to insert.
    Then hit Esc, wait 1 second and the inserted text will appear on every line
    
    0 讨论(0)
  • 2020-11-29 14:48

    You might also have a use case where you want to delete a block of text and replace it.

    Like this

    Hello World
    
    Hello World
    

    To

    Hello Cool
    
    Hello Cool
    

    You can just visual block select "World" in both lines.

    Type c for change - now you will be in insert mode.

    Insert the stuff you want and hit escape.

    Both get reflected vertically. It works just like 'I', except that it replaces the block with the new text instead of inserting it.

    0 讨论(0)
提交回复
热议问题