Vim: Search and Replace, Insert new line

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:
  1. :%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

  1. Mzyzek wrote:

    Intresting, now i know how to find new line in vim…

    Posted 02 Aug 2007 at 7:29 am
  2. Ramnath wrote:

    Thanks I used to format my file.Very useful

    Posted 17 Sep 2007 at 8:53 am
  3. Chris wrote:

    Thank goodness for descriptive blog post titles. Sometimes it’s really hard to know what to search for :D

    Posted 28 Jul 2008 at 7:43 pm
  4. Jero wrote:

    Thanks you for the tip and the title

    Posted 22 Sep 2008 at 5:04 pm
  5. Hugo Estrada wrote:

    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
  6. Hemo wrote:

    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
  7. Casey Wise wrote:

    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
  8. chris wrote:

    worked a treat, thanks!

    Posted 08 Jul 2010 at 1:24 am

Trackbacks & Pingbacks 2

  1. From Simplicity » Blog Archive » Menyisipkan Baris Baru Pada Vim Editor on 03 Jan 2008 at 9:39 am

    [...] http://tech.petegraham.co.uk/2007/05/03/vim-search-and-replace-insert-new-line/ [...]

  2. From links for 2008-06-30 « The Adventures of Geekgirl on 30 Jun 2008 at 1:44 am

    [...] Optimus Pete » Blog Archive » Vim: Search and Replace, Insert new line (tags: code tips vim text edit replace regex regularexpressions) [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *