The Tech Diary

Your Online Notebook!

Tech Diary

Journal your struggles and achievements with technology.
Tags >> vim

Vim: insert line numbers

Posted by: Brad Waite

Tagged in: vim , search and replace

To insert line numbers at the beginning of every line in Vim, do this:

:%s/^/\=line(".")

This is a global search and replace (%s/[search]/[replace]), matching the beginning of each line (^) with an expression (\=) that returns the current line number (line(".")).

To add a comma (or any other character) after the line number, do it like this:

:%s/^/\=line(".") . ","

Any valid Vim expression is valid after the "\=", so you could start line number with 100 like this:

:%s/^/\=100+line(".")

Pretty simple and straightforward, when you think about it.