1

I am trying to write a Perl one-liner in a Bash script to change math-mode delimiters in a LaTeX file from "\[" and "\]" to dollar signs.

That is, I want to change \[a + b = c\] to $a + b = c$.

Unfortunately, I can't figure out how to escape the dollar sign in Perl correctly.

The closest I've gotten is to use perl -pi -e 's/\[/\$/gm' file.tex. However, this inserts \$ into the file instead of a single dollar sign.

2
  • 1
    Did you try using $ without backslash? Commented Jan 15, 2020 at 18:41
  • 1
    I did try using $. Results in an error: Final $ should be \$ or $name at -e line 1, within string Commented Jan 15, 2020 at 18:44

2 Answers 2

5

You aren't inserting \$; you are simply only replacing the [, not \[, with a dollar sign. Compare:

# Wrong
$ perl -p -e 's/\[/\$/gm' tmp.txt
\$a + b = c\]

# Right
$ perl -p -e 's/\\\[/\$/gm' tmp.txt
$a + b = c\]

To replace both,

$ perl -p -e 's/\\\[|\\\]/\$/gm' tmp.txt
$a + b = c$

For what it's worth, you can do this with the standard editor ed, rather than perl, though the escaping gets a little hairy (even switching to tripleee's simpler regular expression for matching either delimiter; it looks the same, but the double \\ are there for printf, not ed, since I'm using | in the substitution operator.):

$ cat tmp.txt
\[a + b = c\]
$ printf 's|\\\[][]|$|g\nwq\n' | ed tmp.txt
14
12
$ cat tmp.txt
$a + b = c$
Sign up to request clarification or add additional context in comments.

Comments

5

No, the problem is that you are replacing a (backslash-escaped) literal [ with a (backslash-escaped) literal dollar sign, but not matching or replacing the literal backslash at all.

Try this.

perl -pi -e 's/\\[][]/\$/g' file.tex

The /m flag didn't seem useful so I took it out.

The square brackets are a character class [...] containing the two literal characters ] and [. They have to be in this order, to keep the expression unambiguous (though it also looks funny). And of course, \\ is a (backslash-escaped) literal backslash.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.