# Write reference of linenumber to file

I want to write the actual linenumbers that a \lineref command generates into an external file. The lines are referenced correctly (after 2 times compiling), but the writing to a file does not work. Here is my MWE, with my (humble) try uncommented to illustrate what I want to do:

\documentclass[10pt,a4paper]{article}
\usepackage{lineno}
\newwrite\tempfile

\begin{document}
\immediate\openout\tempfile=fooref.tex
\begin{linenumbers}*
foo \linelabel{lne:foo1} foo

foo \linelabel{lne:foo2} foo
\end{linenumbers}
\lineref{lne:foo1}
\lineref{lne:foo2}

%\immediate\write\tempfile{\lineref{lne:foo1}} % <- how to do it??
%\immediate\write\tempfile{\lineref{lne:foo2}} % <- how to do it??

\immediate\closeout\tempfile
\end{document}


The resulting fooref.tex should contain just the linenumbers:

1
2


I'm not sure what you'll do with this file, but here's a way to accomplish your need:

\documentclass[10pt,a4paper]{article}
\usepackage{lineno,refcount}

\newwrite\linenumbersfile
\newcommand{\writelineref}[1]{%
\immediate\write\linenumbersfile{\getrefnumber{#1}}%
}

\begin{document}
\immediate\openout\linenumbersfile=\jobname.num
\begin{linenumbers}*
foo \linelabel{lne:foo1} foo

foo \linelabel{lne:foo2} foo
\end{linenumbers}
\lineref{lne:foo1}
\lineref{lne:foo2}

\writelineref{lne:foo1}
\writelineref{lne:foo2}

\immediate\closeout\linenumbersfile
\end{document}


I changed the naming scheme, in order to avoid clobbering files. Correct annotations in the .num file requires two LaTeX runs, as usual when references are dealt with. With \getrefnumber we ensure expandability of the reference.

The .num file contains

1
2


as requested.

• Great, thanks, that works for me. I am writing a tag-macro so that I can tag several lines of text, write them into a file and also get the corresponding linenumbers (e.g. "lines 5 to 7"). With that I start working in Excel. – Felipe Sep 7 '14 at 9:42