home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / unix / question / 15983 < prev    next >
Encoding:
Text File  |  1993-01-28  |  1.5 KB  |  50 lines

  1. Newsgroups: comp.unix.questions
  2. Path: sparky!uunet!ftpbox!news.acns.nwu.edu!nucsrl!ddsw1!dattier
  3. From: dattier@ddsw1.mcs.com (DWT)
  4. Subject: Re: Getting the nth line of a file
  5. Message-ID: <C1Is53.4F2@ddsw1.mcs.com>
  6. Date: Wed, 27 Jan 1993 15:53:27 GMT
  7. References: <1993Jan25.163208.11697@atlantis.uucp> <1993Jan26.151133.18029@atlantis.uucp>
  8. Organization: Contributor Account at ddsw1, Chicago, Illinois  60657
  9. Lines: 39
  10.  
  11. aaron@atlantis.uucp wrote in <1993Jan26.151133.18029@atlantis.uucp>:
  12.  
  13. | I wrote:
  14. | : Is there an easy, elegant, and quick way to get the Nth line of a file in
  15. | : UNIX?  Or, failing that, in C?
  16. | : Currently I use the simple, but somewhat slow:
  17. | : head -n | tail -1
  18. | I received several email replies, which I will summarize here.
  19.  
  20. ... etc.
  21.  
  22. Several people suggested
  23.  
  24. sed -n __p file
  25.  
  26. where "__" is a decimal numeral for the desired line number.  sed __!d file
  27. is equivalent (and shorter to write, but escape the bang if you use *csh).
  28.  
  29. The following should be somewhat faster, as it quits after printing the __th
  30. line instead of reading and discarding the rest of the input:
  31.  
  32. sed -n '__{
  33. p
  34. q
  35. }' file
  36.  
  37. where again "__" is a numeral for the desired line number's position.  You
  38. can put the numeral outside the quotes or use weak quotes instead in case
  39. you'd like to use a variable there.
  40.  
  41. In some later seds it can be condensed to this:
  42.  
  43. sed '__{p;q;}' file
  44.  
  45. David W. Tamkin   Box 59297   Northtown Station, Illinois  60659-0297
  46. dattier@ddsw1.mcs.com    CompuServe: 73720,1570    MCI Mail: 426-1818
  47.