使用sed将“_”,“&”,“$”分别替换为“\_”,“\&”,“\$”。

8
在编写LaTeX时,通常会有一个参考文献文件,其中有时包含_&$。例如,期刊名称“Nature Structural&Molecular Biology”,文章标题“Estimating The Cost Of New Drug Development: Is It Really $802 Million?”以及卷号“suppl_2”。
因此,我需要将这些符号分别转换为\_\&\$,即在前面添加反斜杠,以便LaTeX编译器可以正确识别它们。我想使用sed进行转换。所以我尝试了以下命令:
sed 's/_/\_/' <bib.txt >new.txt

但生成的new.txt与bib.txt完全相同。我认为需要转义_\,所以我尝试了以下代码:

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

但是也没有希望。有人可以帮忙吗?谢谢。

抱歉,我在编辑时看错了。 - rcollyer
1
如果您已经转义了其中一些字符,则您的正则表达式需要检查前一个字符是否不是“\”。 - a'r
4个回答

12

由于shell处理字符串的方式,您遇到了一些困难。反斜杠需要加倍:

sed 's/_/\\_/g'
请确认以下翻译是否符合要求:

需要注意的是,我还添加了一个 'g' 表示替换应该在行上全局应用,而不仅仅是第一个匹配。

要处理所有三个符号,请使用字符类:

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

(替换文本中的“&”是一个特殊字符,指代匹配的文本,而不是字面上的“&”字符。)


3
sed 's/\([_&$]\)/\\\1/g'

e.g.

eu-we1:~/tmp# cat zzz
bla__h&thisis&not the $$end
eu-we1:~/tmp# sed 's/\([_&$]\)/\\\1/g' < zzz
bla\_\_h\&thisis\&not the \$\$end
eu-we1:~/tmp# 

请勿进行原地替换,因为您永远不知道会发生什么。请使用sed 's/([_&$])/\\1/g' < src.tex > dst.tex。 - user237419

1

你需要转义你的\。像这样:sed 's/_/\\_/' new.txt

编辑:此外,要直接修改new.txt,你需要传递-i标志给sed:

sed -iBAK 's/_/\\_/' new.txt


1

你需要对它进行两次转义。

➜  8080667  sed 's/_/\\_/' new.txt
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".
➜  8080667  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接