Linux sed 分别用“\_”、“\&”、“\$”替换“_”、“&”、“$”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8080677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed to replace "_", "&", "$" with "\_", "\&", "\$" respectively
提问by Hymany Lee
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".
在编写 Latex 时,通常有一个参考书目文件,其中有时包含_
, &
, 或$
. 比如期刊名《Nature Structural & Molecular Biology》,文章标题《估计新药开发的成本:真的是8.02亿美元吗?》,卷号“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
所以我需要把这些符号分别转换成\_
、\&
、\$
, 即前面加一个反斜杠,这样latex编译器才能正确识别。我想使用 sed 进行转换。所以我试过了
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
但是生成的new.txt和bib.txt完全一样。我认为_
并且\
需要逃脱,所以我尝试了
sed 's/\_/\\_/' <bib.txt >new.txt
but no hope either. Can somebody help? Thanks.
但也没有希望。有人可以帮忙吗?谢谢。
采纳答案by Michael J. Barber
You're running into some difficulties due to how the shell handles strings. The backslash needs to be doubled:
由于 shell 处理字符串的方式,您遇到了一些困难。反斜杠需要加倍:
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.
请注意,我还添加了一个 'g' 来表示替换应该在行上全局应用,而不仅仅是第一次匹配。
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.)
(替换文本中的&符号是指匹配文本的特殊字符,而不是文字&符号。)
回答by tdenniston
You need to escape your \
. Like this: sed 's/_/\\_/' new.txt
.
你需要逃避你的\
. 像这样:sed 's/_/\\_/' new.txt
。
Edit: Also, to modify new.txt in place, you need to pass sed the -i
flag:
编辑:另外,要修改 new.txt 到位,您需要传递 sed-i
标志:
sed -iBAK 's/_/\\_/' new.txt
sed -iBAK 's/_/\\_/' new.txt
回答by Dogbert
You need to escape it twice.
你需要逃避它两次。
? 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 2 Million?", and the volume number "suppl_2".
? 8080667
回答by user237419
sed 's/\([_&$]\)/\/g'
e.g.
例如
eu-we1:~/tmp# cat zzz
bla__h&thisis¬ the $$end
eu-we1:~/tmp# sed 's/\([_&$]\)/\/g' < zzz
bla\_\_h\&thisis\¬ the $$end
eu-we1:~/tmp#