sd icon indicating copy to clipboard operation
sd copied to clipboard

Error: invalid regex regex parse error: unrecognized escape sequence when used with xargs

Open homocomputeris opened this issue 4 years ago • 2 comments

I have two files

  1. main.tex
\documentclass[12pt,a4paper]{article}
\begin{document}
Reading a Compact Disk requires a disk drive.
\end{document}
  1. glossary.tex
\newglossaryentry{disdr}{name={disk drive},description={A device.}}
\newglossaryentry{cd}{name={Compact Disk},description={A disk.}}

This command works:

cat ./glossary.tex | sd '.*\{(\w+)\}\{.*name=\{(.*?)\},.*|$' '"$2" "\gls{$1}" ./main.tex' | xargs -L 1 sd

resulting

\documentclass[12pt,a4paper]{article}
\begin{document}
Reading a \gls{cd} requires a \gls{disdr}.
\end{document}

But this one

cat ./glossary.tex | sd '.*\{(\w+)\}\{.*name=\{(.*?)\},.*|$' '"$2" "\gls{$1}"' | xargs -L 1 -I _ sd _ "./main.tex"

produces an error:

Error: invalid regex regex parse error:
    disk drive \gls{disdr}
               ^^
error: unrecognized escape sequence
Error: invalid regex regex parse error:
    Compact Disk \gls{cd}
                 ^^
error: unrecognized escape sequence

homocomputeris avatar Mar 19 '21 13:03 homocomputeris

First of all xargs isn’t used correctly.

-I _ sd _ "./main.tex": sd interpretes the _ as a single parameter. Basically this happens: sd "disk drive \gls{disdr}" "./main.tex"

This would work instead:

cat ./glossary.tex | sd '.*\{(\w+)\}\{.*name=\{(.*?)\},.*|$' '"$2" "\gls{$1}"' | xargs -L 1 bash -c 'sd "$0" "$1" "./main.tex"'

But perhaps the author did that on purpose to show us the error.

Therefore, the problem reduces to: Why does this work: sd "x" "\g" ./main.tex But this not:

$ sd "\g" "x" ./main.tex
Error: invalid regex regex parse error:
    \g
    ^^
error: unrecognized escape sequence

If I am not mistaken the answer is as easy as this:

  1. The first argument is parsed as regex pattern, and therefore it needs to be escaped.
  2. The second argument is not a regex pattern, therefore it is not needed there.

Linus789 avatar May 05 '21 20:05 Linus789

Thanks for the excellent explanation @Linus789

chmln avatar May 08 '21 20:05 chmln