Vim has some really useful commands, especially search and replace ones. Unfortunately I'm always forgetting the finer details of how to use them so here's an example:
CODE:
-
:%s/$/\rthis is a new line
To break down whats happening above:
- : switches Vim into command mode
- % means we're going to apply this command to every line in our file
- s means we're using the substitute command. The format of the command is s/search/replacement, 'search' can be a regular expression
- $ tells vim to search for the end of the line
- \rthis is a new line tells vim to replace with a new line character, and to put the text "this is a new line" on that line.
NOTE: \r is used as the new line character when vim is using DOS file format, to find out which file format you are using type :set ff? You can find out more about Vim file formats here.
#Pete Graham
Comments 8
Intresting, now i know how to find new line in vim…
Posted 02 Aug 2007 at 7:29 am ¶Thanks I used to format my file.Very useful
Posted 17 Sep 2007 at 8:53 am ¶Thank goodness for descriptive blog post titles. Sometimes it’s really hard to know what to search for
Posted 28 Jul 2008 at 7:43 pm ¶Thanks you for the tip and the title
Posted 22 Sep 2008 at 5:04 pm ¶Thanks! I was looking for this information, and you saved me a lot of time. I have linked to this page
Posted 29 Apr 2009 at 1:21 am ¶Thank you for this. I work in vi under *nix and was fuddled the Ctrl-VCtrl-M approach wasn’t working on a DOS format file.
Posted 11 Jun 2010 at 8:14 pm ¶Thank you so much for the easily googleable content and helpful post. Saved me a ton of time!
Posted 07 Jul 2010 at 12:39 pm ¶worked a treat, thanks!
Posted 08 Jul 2010 at 1:24 am ¶Trackbacks & Pingbacks 2
[...] http://tech.petegraham.co.uk/2007/05/03/vim-search-and-replace-insert-new-line/ [...]
[...] Optimus Pete » Blog Archive » Vim: Search and Replace, Insert new line (tags: code tips vim text edit replace regex regularexpressions) [...]
Post a Comment