Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If it's not a fixed-record-length file and you don't do some sort of indexing on the line starts, your best bet is to just use:</p> <pre><code>head -n N filespec | tail -1 </code></pre> <p>where <code>N</code> is the line number you want.</p> <p>This isn't going to be the best-performing piece of code for a 3Gb file unfortunately but there are ways to make it better.</p> <p>If the file doesn't change too often, you may want to consider indexing it. By that I mean having <em>another</em> file with the line offsets in it as fixed length records.</p> <p>So the file:</p> <pre><code>0000000000 0000000017 0000000092 0000001023 </code></pre> <p>would give you an fast way to locate each line. Just multiply the desired line number by the index record size and seek to there in the index file.</p> <p>Then use the value at that location to seek in the main file so you can read until the next newline character.</p> <p>So for line 3, you would seek to 33 in the index file (index record length is 10 characters plus one more for the newline). Reading the value there, <code>0000000092</code>, would give you the offset to use into the main file.</p> <p>Of course, that's not so useful if the file changes frequently although, if you can control what happens when things get appended, you can still add offsets to the index efficiently. If you <em>don't</em> control that, you'll have to re-index whenever the last-modified date of the index is earlier than that of the main file.</p> <hr> <p>And, based on your update:</p> <blockquote> <p>Update: If it matters, all the lines have the same length.</p> </blockquote> <p>With that extra piece of information, you don't need the index - you can just seek immediately to the right location in the main file by multiplying the record length by the record length (assuming the values fit into your data types).</p> <p>So something like the pseudo-code:</p> <pre><code>def getline(fhandle,reclen,recnum): seek to position reclen*recnum for file fhandle. read reclen characters into buffer. return buffer. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload