使用 sed 命令将输入​​文本文件中出现的所有字符 '&'、'<'、'>' 替换为其 HTML 实体

问题描述

这是我的输入文本文件

< > & * ^ % $ # @ ! ) ( ) < > < > > > < 

这是我正在使用的 sed shell 脚本。

sed 's/&/&amp;/g ; s/</&lt;/g ; s/>/&gt;/g' html_file.txt > new_file.txt

这是输出文件

<lt; >gt; &amp; * ^ % $ # @ ! ) ( ) <lt; >gt; <lt; >gt; >gt; >gt; <lt; 

我不明白为什么还有 <> 符号而不是 &

解决方法

来自info sed

3.3 The 's' Command
[...]
The 's' command (as in substitute) is probably the most important in
'sed' [...]. The syntax of the 's' command is 's/REGEXP/REPLACEMENT/FLAGS'.
[...]
The REPLACEMENT can contain [...] unescaped '&' characters which reference the
whole matched portion of the pattern space.

使用 &\ 转义到 \&

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...