在 Bash 中转义 HTML 的捷径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12873682/
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
Short way to escape HTML in Bash?
提问by James Evans
The box has no Ruby/Python/Perl etc.
该盒子没有 Ruby/Python/Perl 等。
Only bash, sed, and awk.
只有bash、sed、 和awk。
A way is to replace chars by map, but it becomes tedious.
一种方法是通过映射替换字符,但它变得乏味。
Perhaps some built-in functionality i'm not aware of?
也许一些我不知道的内置功能?
回答by ruakh
Escaping HTML really just involves replacing three characters: <, >, and &. For extra points, you can also replace "and '. So, it's not a long sedscript:
转义HTML实际上只是涉及更换三个大字:<,>,和&。对于加分,您还可以替换"和'。所以,这不是一个很长的sed脚本:
sed 's/&/\&/g; s/</\</g; s/>/\>/g; s/"/\"/g; s/'"'"'/\'/g'
回答by Ivan
You can use recodeutility:
您可以使用recode实用程序:
echo 'He said: "Not sure that - 2<1"' | recode ascii..html
Output:
输出:
He said: "Not sure that - 2<1"
回答by miken32
Pure bash, no external programs:
纯 bash,没有外部程序:
function htmlEscape () {
local s
s=${1//&/&}
s=${s//</<}
s=${s//>/>}
s=${s//'"'/"}
printf -- %s "$s"
}
Just simple string substitution.
只是简单的字符串替换。
回答by schemacs
or use xmlstar Escape/Unescape special XML characters:
或使用 xmlstar Escape/Unescape特殊 XML 字符:
$ echo '<abc&def>'| xml esc
<abc&def>
回答by nachtgeist
The previous sed replacement defaces valid output like
之前的 sed 替换会破坏有效的输出,例如
<
into
进入
&lt;
Adding a negative loook-ahead so "&" is only changed into "&" if that "&" isn't already followed by "amp;" fixes that:
添加否定前瞻,因此“&”仅更改为“&” 如果“&”后面没有跟“amp;” 修复:
sed 's/&(?!amp;)/\&/g; s/</\</g; s/>/\>/g; s/"/\"/g; s/'"'"'/\'/g'

