使用 \immediate\write18 和单引号

使用 \immediate\write18 和单引号

我想使用\immediate\write18(在宏中编码\OuputToFileA)输出包含单引号的字符串。如果我将单引号替换为其他字符,例如X

\StrSubstitute{\@CurrentString}{'}%
    {X}% <---- Replace the single quote
    [\@CurrentString]%

一切正常。但是,我需要输出中的单引号。我尝试了其他任何方法,例如转义单引号:

\StrSubstitute{\@CurrentString}{'}%
    {\@backslashchar\@backslashchar'}% <---- Attempt to escape the single quote
    [\@CurrentString]%

均会生成一个空文件。

使用\immediate\write(参见\OuputToFileB宏)似乎效果不错。我该如何使用它\immediate\write18呢?

期望输出:

之后pdflatex,文件foo.tex应该包含

在此处输入图片描述

笔记:

  • 不是如果当前目录中有,请运行此命令,foo.tex因为它将被覆盖。

代码:

\documentclass{article}
\usepackage{xparse}
\usepackage{xstring}

\immediate\write18{printf "\\n" > foo.tex }% Initialize File

\makeatletter
\NewDocumentCommand{\OuputToFileA}{%
    m% string to output
}{%
    Output A to pdf: #1
    \def\@CurrentString{#1}% 
    %% Using the first \StrSubstitute works. But, I don't want to replace the single quote
    %\StrSubstitute{\@CurrentString}{'}%
    %    {X}% <---- Replace the single quote
    %    [\@CurrentString]%
    \StrSubstitute{\@CurrentString}{'}%
        {\@backslashchar\@backslashchar'}% <---- Attempt to escape the single quote
        [\@CurrentString]%
    %% ---------------------------------
    \immediate\write18{printf 'string = "\@CurrentString"' >> foo.tex }%
    \immediate\write18{printf "\\n" >> foo.tex }%
}
\NewDocumentCommand{\OuputToFileB}{%
    m% string to output
}{%
    Output B to pdf: #1
    \def\@CurrentString{#1}% No escaping required with \immediate
    %% ---------------------------------
    \newwrite\MyFile
    \immediate\openout\MyFile=foo.tex
    \immediate\write\MyFile{\@CurrentString}%
    \immediate\closeout\MyFile%
}
\makeatother

\begin{document}
    \OuputToFileA{\detokenize{Einstein's Formula $E = mc^2$}}%
    %\OuputToFileB{\detokenize{Einstein's Formula $E = mc^2$}}% <-- Works!
\end{document}

答案1

我发现了一个好办法https://stackoverflow.com/a/1250279/923955

'用。。。来代替'"'"'

个人觉得expl3功能比 好太多了xstring,另外\sys_shell_now:n不需要对输入进行扩展,其他的就不用了, 和 交替用起来\sys_shell_now:x更方便。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
% Initialize File
\sys_shell_now:n {printf~"\\n"~>~quotegrill.txt}

\NewDocumentCommand{\OuputToFile}{m}
  {% #1 is the string to write
    Output ~ to ~ pdf: ~ #1
    \str_set:Nn \l_tmpa_str { #1 }
    \str_replace_all:Nnn \l_tmpa_str { ' } { '"'"' }
    \sys_shell_now:x {printf~'string~=~"\l_tmpa_str"'~>>~quotegrill.txt}
    \sys_shell_now:n {printf~"\\n"~>>~quotegrill.txt}
}
\ExplSyntaxOff

\begin{document}

\OuputToFile{Einstein's Formula $E = mc^2$}

\end{document}

输出文件将是


string = "Einstein's Formula $E = mc^2$"

相关内容