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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With