"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!
(written 2011-06-09)
Associated topics are indexed under
P215 - Perl - More about Files [3839] Spraying data from one incoming to series of outgoing files in Perl - (2012-08-15)
[3412] Handling binary data in Perl is easy! - (2011-08-30)
[2964] An introduction to file handling in programs - buffering, standard in and out, and file handles - (2010-09-21)
[2405] But I am reading from a file - no need to prompt (Perl) - (2009-09-14)
[1832] Processing all files in a directory - Perl - (2008-10-11)
[1709] There is more that one way - Perl - (2008-07-14)
[1225] Perl - functions for directory handling - (2007-06-09)
T209 - Tcl/Tk - File and Directory Handling [3617] The fileutil package and a list of file system commands in Tcl - (2012-02-18)
[3429] Searching through all the files in or below a directory - Ruby, Tcl, Perl - (2011-09-09)
[3192] Tcl - Some example of HOW TO in handling data files and formats - (2011-03-04)
[2467] Tcl - catching an error before your program crashes - (2009-10-22)
[1467] stdout v stderr (Tcl, Perl, Shell) - (2007-12-10)
[1426] Buffering up in Tcl - the empty coke can comparison - (2007-11-10)
[1407] Reading from another process in Tcl (pipes and sockets) - (2007-10-26)
[785] Running external processes in Tcl and Tcl/Tk - (2006-06-29)
[779] The fragility of pancakes - and better structures - (2006-06-26)
5711
Some other Articles
Rabbit ShelterIs Melksham town centre dying?How much has Perl (and other languages) changed?Travelling aroundReading the nth line from a file (Perl and Tcl examples)Moving on - a task for the hotel staff!Summer Sunday Trains - outings from Swindon, Chippenham, Melksham, Trowbridge and WestburySelf Portrait (in words)Twitter Phishing Trips ... and a great new alert serviceFriday - Electrician, Food Festival, C++ Course, Rail Group Meeting