Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Search for patterns and add text to end of each line where it occurs

I would like to search for a pattern in vim, and on each line where it occurs, add text to the end of the line. For example, if the search pattern is print( and the text to add is ):

from __future__ import print_function
print('Pausing 30 seconds...'
print("That's not a valid year!"

should become

from __future import print_function
print('Pausing 30 seconds...')
print("That's not a valid year!")
like image 262
David Y. Stephenson Avatar asked Sep 18 '13 20:09

David Y. Stephenson


2 Answers

this command should do it for you:

:g/print(/norm! A)

what it does:

:g/print(/   "find all lines matching the regex
norm! A)     "do norm command, append a ")" at the end of the matched line.

you may want to check

:h :g

for details.

like image 137
Kent Avatar answered Sep 26 '22 02:09

Kent


To add text to the end of a line that begins with a certain string, try:

:g/^print(/s/$/)

See: Power of g - Examples for further explanation.

like image 39
kenorb Avatar answered Sep 23 '22 02:09

kenorb