替换“#"、“$"、“%"、“&"和“_"与“#"、“$"、“\%"、“&"和“\_"

人气:1,026 发布:2022-10-16 标签: escaping latex bash grep sed

问题描述

我有一个纯文本文档,我想在 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

这对吗?

不幸的是,该文件太大而无法在任何 GUI 软件中打开,因此很难使用文本编辑器检查我的 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.

883