Christian has declined my suggestion about using the piped input feature, but I still think it may be interesting to show how it could be used in this case. Note how the argument of the \countfiles macro is pre-processed in order to permit the use of “special” characters, like _ and balanced occurences of { and }, while, at the same time, allowing macros (or, more generally, expandable control sequences) to be expanded, as it is shown below for \myDirName and \jobname.
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
% declare the paper format.
\usepackage[T1]{fontenc} % Not always necessary, but recommended.
% End of standard header. What follows pertains to the problem at hand.
\newcounter{numberOfFiles}
\makeatletter
% Beware: "special" characters like "_" that appear in the directory name must
% be either re-"\catcode"d or "\detokenize"d: the latter method is **much**
% simpler than the former, but it does **not** cope with filenames containing
% the "%" character, or unbalanced "{" and "}" characters, and in addition it
% requires e-TeX extensions (not at all a concern, these days!).
\newcommand*{\countfiles}[1]{%
\begingroup
\protected@edef\@tempa{#1}% before detokenizing, expand expandable (and
% unprotected) tokens
% We use "\@inputcheck" for the temporary input pipe:
\openin\@inputcheck "|ls -1 % the last character is the digit "one"
\expandafter\detokenize\expandafter{\@tempa} % space meant
|wc -l% the last character is the letter "ell"
"\relax % without the "\relax", the ensuing "\ifeof" would be
% prematurely expanded
\ifeof\@inputcheck
% An error message could be triggered here.
\typeout{WARNING: Could not read \protect\numFiles!}%
\else
\endlinechar \m@ne % cf. exercise 20.18
\readline\@inputcheck to\@tempa
\setcounter{numberOfFiles}{\@tempa}%
\fi
\closein\@inputcheck % note: no "\immediate" needed for "\closein"
\endgroup
}
\makeatother
\newcommand*{\myDirName}{some_directory}
\begin{document}
\setcounter{numberOfFiles}{-1}\countfiles{\myDirName}
There are \arabic{numberOfFiles} files in the specified directory.
\bigbreak
\setcounter{numberOfFiles}{-1}
In the current directory there are:
\begin{tabbing}
\quad 999\=\kill
\countfiles{\jobname.*}\>\arabic{numberOfFiles}\'
file(s) whose basename is \texttt{\jobname};\\
\countfiles{*.{tex,log}}\>\arabic{numberOfFiles}\'
file(s) whose extension is either \texttt{.tex} or \texttt{.log};\\
\countfiles{[A-Za-z]*.tex}\>\arabic{numberOfFiles}\'
file(s) whose name consists only of letters, followed by the
extension \texttt{.tex}.
\end{tabbing}
That's all, folks!
\end{document}
bashfuland a tiny shell script? – Mar 01 '17 at 19:25