In Linux/Unix, there are almost always multiple ways to do common tasks. Just for completeness, here are some other ways you can do it besides the obvious:
pr -t -n [file]
From an old command to format text to send to a line printer. The '-t' will omit header and footer information that are not relevant to a terminal.
Here's a cute sed method that prints the line number on every other line. We use 'paste' to fold them into a single line:
sed = /etc/passwd | paste - -
Or, we can use the one true editor, ed:
echo '1,$n' | ed -s [file]
Or, ex, vi's non-cursor-addressing predecessor:
printf 'set number\ng/^/p\n' | ex /etc/passwd
And one final complicated answer, requiring ksh93 or bash (and the seq command. Using the .. range and an eval statement is left as an exercise):
paste <(seq $(wc -l < [file])) [file]
Tested on Debian Linux, FreeBSD, and Solaris 10 (the last fails there because of no 'seq').
nltreats lines that contain a sequence of 1, 2 or 3\:strings specially. Use-d $'\n'to avoid that. Also, by default, it doesn't number empty lines. Use-bato number every line. – Stéphane Chazelas Jan 30 '18 at 15:57$'...'syntax is bash-specific. – myrdd Nov 06 '18 at 16:17seqdidn't do it. Thank god fornl– Sridhar Sarnobat Jan 09 '19 at 17:56$'...'comes from ksh93 and is also supported byzsh,mksh, busybox sh, FreeBSD sh and bash at least. It's not standard yet, but is planned for inclusion in the next major POSIX version. – Stéphane Chazelas Feb 19 '19 at 10:08$'...'(ANSI-C Quoting) portability: https://unix.stackexchange.com/questions/371827/do-shells-other-than-bash-and-zsh-support-ansi-c-quoting-e-g-string – myrdd Feb 19 '19 at 16:20nlcan set a starting number with-v. – Onnonymous Jun 12 '19 at 07:00