Convert \input to number

I'm reading several txt-files from disk and I want to do some simple calculations on them and be able to print them on the page.

Basically I have:

\newcommand\getinput[2]{
\immediate\write18{do-some-things > input.txt}
\input{input.txt}}


And now I want to do use that input for simple additions, like this:

\newcounter{mycounter}
My Input: \getinput
My Sum: \themycounter

• you could do \newcommand\getinput[2]{\input{|do-some-things}} so the output is piped straight to tex with no intermediate file (although you'd still have to make it a number) May 14, 2020 at 11:09
• Do you need to use exactly \getinput in the counter setting? Or can we use a route where you call the input and save the result in a macro? May 14, 2020 at 11:18
• @DavidCarlisle I'm using it for executing texcount to count words in my sections. That's why I need to write it to file first May 14, 2020 at 11:48
• @JosephWright sure. It doesn't matter if there are any extra steps May 14, 2020 at 11:49
• @RazorHail why do you need to write to a file though you can pipe the output straight to tex. May 14, 2020 at 11:51

You will need this to work by expansion if you want to use it directly for a counter, so cannot use \write. Instead, it's possible to exploit the piped input ability of modern engines. Using a working example with echo

\documentclass{article}
\makeatletter
\newcommand\getinput{\@@input|"echo 1"}
\makeatother
\begin{document}

\newcounter{mycounter}
My Input: \getinput
My Sum: \themycounter

\end{document}


Here, we need the 'raw' behaviour of the \input primitive, hence needing to use it's LaTeX name, \@@input.

If you are happy with a two-step process, first saving the information then using it, you might use the more robust expl3 wrapper around the same idea.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand \saveinput { m m }
{ \sys_get_shell:nnN {#1} { } #2 }
\ExplSyntaxOff
\begin{document}

\newcounter{mycounter}
\saveinput{echo 1}\savedinput

My Input: \savedinput
My Sum: \themycounter

\end{document}

• Great. Thank you. I just used the second method and replaced "echo 1" with "cat input.txt" May 14, 2020 at 14:01
\documentclass{article}
\newcounter{tmpcnt}
\newwrite\notesfile
\newcommand\getinput[1]{
\immediate\openout\notesfile=input.txt
\immediate\write\notesfile{\the\numexpr#1+\thetmpcnt\relax}
\immediate\closeout\notesfile