在Bash中逃避HTML的简短方法?

Jam*_*ans 29 bash html-entities

这个盒子没有Ruby/Python/Perl等.

只有bash,sedawk.

一种方法是用地图替换字符,但它变得乏味.

也许我不知道一些内置功能?

rua*_*akh 43

转义HTML实际上只是涉及更换三个大字:<,>,和&.对于额外的积分,您也可以替换"'.所以,这不是一个很长的sed脚本:

sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&#39;/g'
Run Code Online (Sandbox Code Playgroud)

  • +1 优雅和高效。你应该在这里发布你的答案:http://stackoverflow.com/questions/5929492/bash-script-to-convert-from-html-entities-to-characters 他们建议安装`recode`、`perl`、`php `、`xmlsarlet` 和 `w3m`(用于大声喊叫的网络浏览器)。最后一个答案建议使用 Python3,尽管默认情况下安装(至少在 Ubuntu 中)也太过分了。 (2认同)

Iva*_*van 9

你可以使用recode实用程序:

    echo 'He said: "Not sure that - 2<1"' | recode ascii..html
Run Code Online (Sandbox Code Playgroud)

输出:

    He said: &quot;Not sure that - 2&lt;1&quot;
Run Code Online (Sandbox Code Playgroud)

  • 如果没有 Python/Ruby/Perl,可能无法使用。 (3认同)

mik*_*n32 7

纯 bash,没有外部程序:

function htmlEscape () {
    local s
    s=${1//&/&amp;}
    s=${s//</&lt;}
    s=${s//>/&gt;}
    s=${s//'"'/&quot;}
    printf -- %s "$s"
}
Run Code Online (Sandbox Code Playgroud)

只是简单的字符串替换。