替换"#"," $","%","&放大器;"和" _"与" \\#"," \\ $"," \\%QUOT;," \\&安培;"和" \\ _" [英] Replacing "#", "$", "%", "&", and "_" with "\#", "\$", "\%", "\&", and "\_"
问题描述
我有一个纯文本文件,我想里面编译LaTeX的。但是,有时它具有字符#,$,%,&放大器;,和_。在LaTeX的正确编译,我必须首先以#,\\ $,\\%,将这些字符替换\\&安培;和_。我在使用该行 SED
:
I have a plain text document, which I want to compile inside LaTeX. However, sometimes it has the characters, "#", "$", "%", "&", and "_". To compile properly in LaTeX, I must first replace these characters with "#", "\$", "\%", "\&", and "_". I have used this line in sed
:
sed -i 's/\#/\\\#/g' ./file.txt
sed -i 's/\$/\\\$/g' ./file.txt
sed -i 's/\%/\\\%/g' ./file.txt
sed -i 's/\&/\\\&/g' ./file.txt
sed -i 's/\_/\\\_/g' ./file.txt
这是正确的?
不幸的是,这个文件太大无法打开任何图形用户界面软件,因此检查,如果我的 SED
行是用文本编辑器正确是困难的。我试着用的grep
搜索,但如预期的搜索无法正常工作(例如下面,我搜索包含$的行):
Unfortunately, the file is too large to open in any GUI software, so checking if my sed
line is correct with a text editor is difficult. I tried searching with grep
, but the search does not work as expected (e.g. below, I searched for any lines containing "$"):
grep "\$" file.txt
- 什么是把\\在这些字符前面的最佳方式?
- 如何使用
的grep
来成功地检查线路的替代品? - What is the best way to put "\" in front of these characters?
- How can I use
grep
to successfully check the lines with the replacements?
推荐答案
您可以做一个单一的电话更换为 SED
:
You can do the replacement with a single call to sed
:
sed -i -E 's/([#$%&_\])/\\&/g' file.txt
的&安培;
在替换文本填写的任何单个字符用括号括起来。请注意,由于 \\
是LaTeX的转义字符,你必须逃脱它,以及在原始文件。
The &
in the replacement text fills in for whichever single character is enclosed in parentheses. Note that since \
is the LaTeX escape character, you'll have to escape it as well in the original file.
这篇关于替换"#"," $","%","&放大器;"和" _"与" \\#"," \\ $"," \\%QUOT;," \\&安培;"和" \\ _"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!