Main Content

Reading the nth line from a file (Perl and Tcl examples)

Archive - Originally posted on "The Horse's Mouth" - 2011-06-09 07:36:33 - Graham Ellis

"How do I find the 100th line in a file" - a common question for newcomers to coding. The short answer is to open the file, and loop through to read lines until the one that you want. Although most languages have a seek command or function, that works by bytes and with a typical text / ascii file, line lengths vary so that you don't know exactly where to seek if you try to use it.

As an alternative, in some circumstances you may wish to read the whole file into a list / array and then look by line number - in Perl:

  open FH,"rails_routes";
  @lines = <FH>;
  print $lines[39];


or read the whole file into a string and then turn it into a list - in Tcl:

  set fp [open rails_routes]
  set stuff [read $fp]
  set lines [split $stuff "\n"]
  puts [lindex $lines 39]


but in such cases you need to be careful if the file's potentially huge.

Where a large file is accessed a lot by record number, and doesn't change often, you might consider setting up an index or (say) every thousandth line, so that you can seek most of the way to what you want - or perhaps you should be using a database rather than a plain file if you have that requirement. Isn't it wonderful how technologys go together!