[Tex/LaTex] Numbers in Newcommand

macrosxetex

I have some thousands of special text lines specifically numbered.

001001=aaaaaaaa
001002=bbbbbbbb
001003=cccccccc

002001=dddddddd
002002=mmmmmmmm
002003=jjjjjjjj

003001=uuuuuuuu
003002=iiiiiiii
003003=vvvvvvvv

etc.

In my Latex file I want to insert that specific assigned text with a simple number entry such as 001001 or perhaps \001001 , which in return will show aaaaaaaa once compiled. How can I do this?

Please note that I've already studied following Q&A's but still couldn't come up with a good result, not could I use \catcode. I use xetex and polyglossia if that makes difference.

Best Answer

An approach without external packages can be as follows:

\documentclass{article}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.dat}
001001=aaaaaaaa
001002=bbbbbbbb
001002=cccccccc

002001=dddddddd
002002=mmmmmmmm
002003=jjjjjjjj

003001=uuuuuuuu
003002=iiiiiiii
003003=vvvvvvvv
\end{filecontents*}

\makeatletter
\newread\nina@read
\newcommand{\grabdata}[1]{%
  \begingroup\endlinechar=\m@ne
  \openin\nina@read=#1\relax
  \loop\ifeof\nina@read\else
    \read\nina@read to \@tempa
    \nina@convert
  \repeat
  \closein\nina@read
  \endgroup}
\def\nina@convert{%
  \if\relax\detokenize\expandafter{\@tempa}\relax\else
    \expandafter\nina@convert@i\@tempa\relax
  \fi}
\def\nina@convert@i#1=#2\relax{%
  \global\@namedef{nina@data@#1}{#2}}
\newcommand{\numentry}[1]{\@nameuse{nina@data@#1}}
\makeatother

\grabdata{\jobname.dat}


\begin{document}

\numentry{001001}

\numentry{001002}

\numentry{001003}

\numentry{002001}

\numentry{002002}

\numentry{002003}

\numentry{003001}

\numentry{003002}

\numentry{003003}

\end{document}

I've used \jobname.dat as the file name just not to clobber my existing files.

If the data file is named foo.xyz you'll use

\grabdata{foo.xyz}

and then the data will be available in the form

\numentry{001001}

The data file is read line by line and each line is split at the = token to get the key and the value. So if the line is

001001=aaaaaaaa

we essentially do

\@namedef{nina@data@001001}{aaaaaaaa}

(globally, as we use \endlinechar=-1 to avoid spurious spaces and get rid of empty lines).

Related Question