Show Line Numbers with Vi

This is a fairly common task. Usually when you are configuring an application, you will get something that says like “now go to line 293 and change this word….” if you are only counting by hand, that’s quite a goal to accomplish. Here’s the quick and easy way

Prerequisites

this can be done logged in as any user

Line numbers are a display setting of the editor only; nothing is added to the file itself.

bash-4.1$ prompt as a regular user

1) Open the file

let’s edit the sample file OffsiteBackup.sh

vi OffsiteBackup.sh at the bash prompt

as you can see there are many lines in this script

OffsiteBackup.sh open in vi without line numbers: #!/bin/sh header comments and Variables block

2) Turn on line numbers

Let’s hit our magic keys, CTRL+C

Vim message after Ctrl+C: Type :quit<Enter> to exit Vim

you should notice the above appear at the bottom of you screen

In vim, Ctrl+C simply interrupts and returns you to normal mode, which is why it prints that hint. Pressing Esc does the same job and is the usual way to make sure you are in normal (command) mode before typing a colon command.

from here enter :set nu, and hit enter

:set nu typed at the vi command line

there we have it, line numbers in our VI window!

OffsiteBackup.sh in vi with line numbers 1 to 15 shown down the left side

Handy related commands

:set nu          " show line numbers (long form :set number)
:set nonu        " hide them again
:set nu!         " toggle on/off
:set rnu         " relative numbers (vim), handy with 5j or 3dd
:293             " jump to line 293
293G             " same, from normal mode
:set ruler       " show the current line and column in the status line

You can also open a file directly at a line from the shell:

vi +293 /etc/httpd/conf/httpd.conf

Make it permanent

Add the setting to your editor startup file so every session shows numbers:

echo "set number" >> ~/.vimrc

That is for vim. Classic vi (for example on Solaris) reads ~/.exrc instead, where the same set number line works.

Troubleshooting

  • Typing :set nu inserts text into the file: you were still in insert mode. Press Esc first, then type the colon command.
  • The numbers are gone next time: :set nu lasts only for the current session; use the startup file above.
  • Numbers are not saved in the file: correct, they are display only. To print a file with numbers in the shell use cat -n file or nl file.
  • On RHEL, AlmaLinux and Rocky 9/10, vi is the small vim-minimal build and vim comes from the vim-enhanced package; the colon commands above work in both.

That’s it!

Hosted Linux Servers at www.zwiegnet.com/go

Related guides: find shared libraries for binary ldd · Downgrade package CentOS 6 · Developing Applications for RHEL/CentOS

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *