2

I have a directory that contains multiple files. I can easily determine the presence or absence of a file with the following command.

\IfFileExists{sample.png}{....}{}

But how can I check the presence of a file which starts with a specific string. For example suppose there are the following files in my folder:

mapScan.png
mapTest.png
sample.tex

I am going to have an If condition that checks the presence of file which start with map.

Point: I should use pdflatex as LaTeX compiler.

1
  • You can't, because TeX needs a full file name to find a file (unless you use -shell-escape and something like map*) Apr 5 at 19:43

1 Answer 1

2

This needs to enable shell-escape.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\IfGenericFileExistsTF}{mmm}
 {
  \sys_get_shell:nnN { kpsewhich~#1 } { \cctab_select:N \c_code_cctab } \l_tmpa_tl
  \tl_if_blank:VTF \l_tmpa_tl { #3 } { #2 }
 }

\ExplSyntaxOff

\IfGenericFileExistsTF{map*.png}{\typeout{YES}}{\typeout{NO}}

\IfGenericFileExistsTF{Map*.png}{\typeout{YES}}{\typeout{NO}}

\stop

In my test setting there are two files mapScan.png and mapTest.png, but no file starting with Map. The console would print

YES
NO

for the two shown commands. The setting of \c_code_cctab is used to ignore spaces (and endlines).

You can use whatever set of commands you want in the second and third arguments to \IfGenericFileExistsTF.

Alternative implementation with l3sys-shell:

\documentclass{article}
\usepackage{l3sys-shell}

\ExplSyntaxOn

\NewDocumentCommand{\IfGenericFileExistsTF}{mmm}
 {
  \sys_shell_split_ls:nN { #1 } \l_tmpa_seq
  \tl_if_blank:eTF { \seq_item:Nn \l_tmpa_seq { 1 } } { #3 } { #2 }
 }

\ExplSyntaxOff

\IfGenericFileExistsTF{map*.png}{\typeout{YES}}{\typeout{NO}}

\IfGenericFileExistsTF{Map*.png}{\typeout{YES}}{\typeout{NO}}

\stop

Explanation: if there is no match, the sequence will contain a single empty item.

5
  • You could use l3sys-shell to get the directory listing in a system-agnostic fashion
    – Joseph Wright
    Apr 5 at 21:35
  • @JosephWright Not sure what you mean, but I replaced ls with kpsewhich, which is in fact OS independent.
    – egreg
    Apr 5 at 21:37
  • I was thinking of \sys_shell_split_ls:nN, but using kpsewhich as you say also works :)
    – Joseph Wright
    Apr 5 at 21:39
  • @JosephWright Added. But perhaps the sequence should be empty if the listing returns nothing, rather than having an empty item. Not a big deal anyway.
    – egreg
    Apr 5 at 22:10
  • I'll look at that
    – Joseph Wright
    Apr 6 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.