How to add line numbers to a text file?

Jeff Beadles jeff at onion.pdx.com
Sun Dec 2 16:55:35 AEST 1990


In <6826 at uceng.UC.EDU> dmocsny at minerva.che.uc.edu (Daniel Mocsny) writes:
...
>My question to all of you, however, is this: faced with the need to
>number a text file from a shell script, how would you do it? I'm
>kind of curious to see the variety of approaches possible. Would you
>use C, awk, perl, sed, sh, cat, echo, expr, and/or dd?

Well, here's a couple:

	cat -n $file

	pr -n -t $file  (You missed pr :-)

	awk '{ print NR, $0}' $file

These all assume you want them numbered in decimal.

To number in hex and octal use:

	awk '{ printf("%x %s\n", NR, $0) }' $file		# Hex
	awk '{ printf("%o %s\n", NR, $0) }' $file		# Octal

Some system's don't support "cat -n".  (I think SYSVR3 ??)  The awk solution
should work most anywhere.

Have fun!

	-Jeff
-- 
Jeff Beadles		jeff at onion.pdx.com



More information about the Comp.unix.questions mailing list