在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:32:30  来源:igfitidea点击:

Short way to escape HTML in Bash?

bashhtml-entities

提问by James Evans

The box has no Ruby/Python/Perl etc.

该盒子没有 Ruby/Python/Perl 等。

Only bash, sed, and awk.

只有bashsed、 和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/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&#39;/g'

回答by Ivan

You can use recodeutility:

您可以使用recode实用程序:

    echo 'He said: "Not sure that - 2<1"' | recode ascii..html

Output:

输出:

    He said: &quot;Not sure that - 2&lt;1&quot;

回答by miken32

Pure bash, no external programs:

纯 bash,没有外部程序:

function htmlEscape () {
    local s
    s=${1//&/&amp;}
    s=${s//</&lt;}
    s=${s//>/&gt;}
    s=${s//'"'/&quot;}
    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
&lt;abc&amp;def&gt;

回答by nachtgeist

The previous sed replacement defaces valid output like

之前的 sed 替换会破坏有效的输出,例如

&lt;

into

进入

&amp;lt;

Adding a negative loook-ahead so "&" is only changed into "&amp;" if that "&" isn't already followed by "amp;" fixes that:

添加否定前瞻,因此“&”仅更改为“&” 如果“&”后面没有跟“amp;” 修复:

sed 's/&(?!amp;)/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&#39;/g'