Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed to replace "_", "&", "$" with "\_", "\&", "\$" respectively

Tags:

linux

sed

latex

In writing latex, usually there is a bibliography file, which sometimes contains _, &, or $. For example, the journal name "Nature Structural & Molecular Biology", the article title "Estimating The Cost Of New Drug Development: Is It Really $802 Million?", and the volume number "suppl_2".

So I need to convert these symbols into \_, \&, and \$ respectively, i.e. adding a backslash in front, so that latex compiler can correctly identify them. I want to use sed to do the conversion. So I tried

sed 's/_/\_/' <bib.txt >new.txt

but the generated new.txt is exactly the same as bib.txt. I thought _ and \ needed to be escaped, so I tried

sed 's/\_/\\\_/' <bib.txt >new.txt

but no hope either. Can somebody help? Thanks.

like image 842
Jacky Lee Avatar asked Nov 10 '11 14:11

Jacky Lee


1 Answers

You're running into some difficulties due to how the shell handles strings. The backslash needs to be doubled:

sed 's/_/\\_/g'

Note that I've also added a 'g' to indicate that the replacement should applied globally on the lines, not just to the first match.

To handle all three symbols, use a character class:

sed 's/[_&$]/\\&/g'

(The ampersand in the replacement text is a special character referring to the matched text, not a literal ampersand character.)

like image 78
Michael J. Barber Avatar answered Sep 29 '22 11:09

Michael J. Barber