Filesystem Access – How to Read Arbitrary Lines from a File

filesystem-access

Is there an easy way to read arbitrary lines from a file? For example "read line number 12" or "read backwards from last line to first line" or "read lines 1,3,5…".

Best Answer

No, you can't read arbitrary lines, but you can't do that in most other programming languages either. You have to read line after line from the beginning. Apart from the \read primitive, there is also the \readline primitive which reads a line verbatim. You can use that to save all lines in macros and use these afterward:

\newread\myread
\newcount\linecnt
\openin\myread=file.dat
\@whilesw\unless\ifeof\myread\fi{%
  \advance\linecnt by \@ne
  \readline\myread t\expandafter o\csname line-\number\linecnt\endcsname
}
Related Question