【问题标题】:sed to replace "_", "&", "$" with "\_", "\&", "\$" respectivelysed 将“_”、“&”、“$”分别替换为“\_”、“\&”、“\$”
【发布时间】:2011-11-10 14:02:29
【问题描述】:

在编写latex时,通常有一个参考书目文件,有时会包含_&$。例如,期刊名称“Nature Structural & Molecular Biology”,文章标题“Estimating The Cost Of New Drug Development: Is It Is It really $8.02M?”,卷号“suppl_2”。

所以我需要将这些符号分别转换成\_\&\$,即在前面加一个反斜杠,这样latex编译器才能正确识别它们。我想使用 sed 进行转换。所以我尝试了

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

但是生成的 new.txt 和 bib.txt 完全一样。我认为_\ 需要转义,所以我尝试了

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

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

【问题讨论】:

  • 抱歉,我在编辑时误读了。
  • 如果您已经转义了其中一些字符,那么您的正则表达式将需要检查前一个字符是否不是“\”。

标签: linux latex sed


【解决方案1】:

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

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

请注意,我还添加了一个“g”来表示替换应该全局应用于行,而不仅仅是第一个匹配项。

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

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

(替换文本中的 & 是指匹配文本的特殊字符,而不是文字 & 字符。)

【讨论】:

    【解决方案2】:
    sed 's/\([_&$]\)/\\\1/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# 
    

    【讨论】:

    • 不要做就地seds,你永远不知道。做 sed 's/([_&$])/\\\1/g' dst.tex
    【解决方案3】:

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

    编辑:另外,要修改 new.txt,您需要传递 sed -i 标志:

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

    【讨论】:

      【解决方案4】:

      你需要转义两次。

      ➜  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  
      

      【讨论】:

        猜你喜欢
        • 2013-08-31
        • 2021-05-23
        • 2021-12-18
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        相关资源
        最近更新 更多