Physics314
Physics314

Reputation: 351

SED: Search and replace two expressions with backslash

I am attempting to search and replace a string using sed. Both the search and replace strings have backslashes in them. For example

var="\text{kpll}"
var2="k_{\parallel}"

sed -i.bak "s|$var|$var2|g" MathematicaToLaTex.tex

This does not work as expected. I was expecting to have

\text{kpll} ---> k_{\parallel}

Instead, I am getting

\text{kpll} ---> \k_{parallel}

It seems that sed is correctly finding the string \text{kpll} just fine, but it is not replacing it accurately. Have looked through the forums but could not find a solution. Have tried changing delimiters, using ' instead of ", but to no avail. Have also tried changing the file type from .tex to .txt, but made no difference. Running this in Terminal in MacOS.

------- Edit -------

I required both changing the single backslash to a double, and changing the variable name quotes from " to ' for it to work.

Upvotes: 1

Views: 111

Answers (1)

Cyrus
Cyrus

Reputation: 88999

Escape the backslash and replace " with ':

var='\\text{kpll}'
var2='k_{\\parallel}'
sed -i.bak "s|$var|$var2|g" MathematicaToLaTex.tex

Upvotes: 3

Related Questions