6

For labelling purposes I want to print the filename with extension given a full file path (in \tt font)

Based on Egreg's answer in Only get filename and extension of listing, not whole path I cooked up this command, but I doesn't work with underscores and all my attempts to modify it accordingly failed so far:

\documentclass{article}
\usepackage{listings}
\usepackage{url}

\makeatletter
\DeclareRobustCommand{\filename}[1]{%
 \begingroup
  % \lstname seems to change hyphens into \textendash
  \def\textendash{-}%
  \filename@parse{#1}%
  \texttt{\filename@base.\filename@ext}%
 \endgroup
}
\makeatother


\begin{document}
    Works: \filename{path/to/file.txt} % prints: file.txt

    Fails: \filename{path/to/file_2.txt} % should print: file_2.txt
\end{document}

I also tried building a similar command the xstring package, but that didn't work out for me either. Thanks for your help!

5

You can stringify \filename@base before using it:

\documentclass{article}
\usepackage{listings}
\usepackage{url}

\makeatletter
\DeclareRobustCommand{\filename}[1]{%
 \begingroup
  % \lstname seems to change hyphens into \textendash
  \def\textendash{-}%
  \filename@parse{#1}%
  \edef\filename@base{\detokenize\expandafter{\filename@base}}%
  \texttt{\filename@base.\filename@ext}%
 \endgroup
}
\makeatother

\begin{document}

\filename{path/to/file.txt} % prints: file.txt

\filename{path/to/file_2.txt} % should print: file_2.txt

\end{document}

enter image description here

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.