How to add line numbers to file being edited in vi?

I have some text and I use :number in command mode to get number in each line and besides this I also want to have this number at saved output. What method/command can I use to achieve this?

Upvotes: 2

Views: 232

Answers (3)

Jens
Jens

Reputation: 72639

Use the power of Unix utilities with the power of vi filtering. There are several utilities that number text files: nl(1), but also cat(1) (assuming it supports the non-POSIX -n option). When you are in vi, run this command to filter the whole file through cat -n:

:%!cat -n

You could also use

:%!nl

but note that nl by default does not number empty lines, while cat does. To number all lines with nl, use

:%!nl -b a

Upvotes: 2

Thor
Thor

Reputation: 47099

You can use this vim tip:

%s/^/\=printf('%-4d', line('.'))

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

Use the command nl.

i.e.

nl <in.txt > out.txt

Upvotes: 1

Related Questions