Replace multiple lines in Vim
Aim
// to replace the following line with new multiple lines
// original line
"type": "string"
// target lines
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
scripts
%s/"type": "string"$/"type": "string",\r "fields": {\r "raw": {\r "type": "string",\r "index": "not_analyzed"\r }\r }/g
// explainations
0, %s
means to do the matching and replacing over all the lines in this document
1, $
here denotes the end of this line. So it means this line should end up with "type": "string"
2, \r
here denotes a ‘NEW LINE’. It is quite similar to \n
. If we are to match multiple lines in the original text, then we will use \n
to match that. And if we are to create new lines in the new text, we are about to use \n
.
An example from google group to demonstrate this:
<br>
<br>
<br>
to be replaced by
</tr>
</tbody>
</table>
Then we shall use the script like:
:s/<br>\n<br>\n<br>\n/<\/tr>\r<\/tbody>\r<\/table>\r/
source of google group: https://groups.google.com/forum/#!topic/comp.editors/MSAbbQGdNnI