Skip to content

## Read number lines in a file - in LaTeX

Probably a rare needed feature, but i had to count the number lines in a text file - in LaTeX.

Counting the line numbers is done by using a counter (what else, eh?) and readling the file line by line:

\documentclass{book}

\usepackage{ifthen}

\newcounter{FileLines}
\newboolean{RestFile}
\newcommand{\FileLine}{}
\newread\File

\newcommand{\CountLinesInFile}[2]
{
\setboolean{RestFile}{true}
\setcounter{FileLines}{0}

\openin\File=#1
\whiledo{\boolean{RestFile}}
{
\ReadNextLine{\File}
\ifthenelse{\boolean{RestFile}}{
\stepcounter{FileLines}
}{}
}
\closein\File
}

\newcommand{\ReadNextLine}[1]{
\ifthenelse{\boolean{RestFile}}{
\read#1 to \FileLine
\ifeof#1\setboolean{RestFile}{false
}
\else % if last line already is read, EOF appears here
\fi
}{}
}

\begin{document}

\CountLinesInFile{textfile.txt}

Lines in file: \arabic{FileLines}

\end{document
}

\File is a TeX file descriptor. Note that TeX has a very limited number of this file descriptors, but fortunately they can be re-used, as long as the descriptor is not used in parallel by different commands for a different operation.

The number of file lines is available in the \FileLines counter, which can be exported in arabic numerals by using \arabic{}.

More possible counter representations are explained in my previous post.

No Trackbacks

### Comments

Display comments as Linear | Threaded

#### Jonas Winkler on Wednesday, February 5. 2014:

Thanks for sharing, exactly what I was looking for. Works like a charm :)
Comments ()