How to add line numbers to a text file?

P E Smee exspes at gdr.bath.ac.uk
Thu Dec 6 22:54:02 AEST 1990


In article <4905 at segue.segue.com> jim at segue.segue.com (Jim Balter) writes:
>In article <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?
>
>pr -tn filename
>grep -n $ filename
>
>If you simply RTFM (permuted index), you'll find
>nl filename on PWB/SVID based systems, and
>num filename (cat -n) on BSD

I've gotten to feel like the poor guy who posted this has gotten an
inordinate amount of flak, so I feel compelled to post.  Jim, I'm not
accusing you of providing the flak.  I picked yours to hang off of
because I wanted to agree that the permuted index is overlooked far too
often, and your suggestion for looking there as a first guess is
probably one of the most useful suggestions.

To everyone else, note that Dan didn't say he didn't know how to do
this, he said he was interested in comparing the methods used by
different people.  TFM doesn't help there.  Also, note that the problem
is system dependent anyway.  (Assuming standard versions, no local or
manufacturer-specific enhancements):

  nl       is not available under BSD (the one true Unix), V7, or Xenix
           prior to 3.0.  Further, the -p option is SysV only; depends 
           on what you want the file numbered for, but for some purposes
           -p is the 'right' way.

  cat -n   is only available in BSD.  Not as much control over style as
           nl.

  grep -n  is probably the most portable easy way, if you want ALL lines
           numbered.  I don't believe you could force it into 'nl -p'
           behavior, since any selector used to determine which lines are
           to be numbered also determines which lines are output.  So,
           not interesting for some purposes.

  awk      if you want to do it portably, and don't do it often enough
           to make writing a C program worthwhile, and want something
           other than 'all lines numbered', awk is probably the way to go.

My guess would be that any of these would be better than building a
numberer from 'shell parts' (echo, etc).  If I had to do it often and
portably, I'd probably hack together a special purpose C program to do
it, for speed as compared to grep or awk.  Since I don't do it often,
that's not worth it.

-- 
Paul Smee, Computing Service, University of Bristol, Bristol BS8 1UD, UK
 P.Smee at bristol.ac.uk - ..!uunet!ukc!bsmail!p.smee - Tel +44 272 303132



More information about the Comp.unix.questions mailing list