Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for string and add line in vi/vim

Tags:

vim

vi

I'm trying to edit a config file and want to add a specific line of code (on a newline) whenever a specific string is matched...everything I've searched for does search and replace, I'm looking for search and append...

like image 985
user1172482 Avatar asked Jan 26 '12 23:01

user1172482


2 Answers

personally, i think using ":g" command is probably better than ":s" for this problem.

:g/key/norm owhat ever you want

will make text:

foo
bar
key
foo2
bar2
key2
blah

to:

foo
bar
key
what ever you want
foo2
bar2
key2
what ever you want
blah

if you want to add the new line above the line containing the pattern, just change the small "o" to "O".

like image 133
Kent Avatar answered Sep 20 '22 21:09

Kent


In vim \r is the new-line. So you can do something like this

%s/search string/&\rnew code/
like image 22
jaypal singh Avatar answered Sep 21 '22 21:09

jaypal singh